Поделиться через


Практическое руководство. Создание файлов и каталогов в изолированном хранилище

После получения хранилища в нем можно создавать каталоги и файлы для хранения данных. Внутри хранилища имена каталогов и файлов указываются относительно корневого каталога виртуальной файловой системы.

Чтобы создать каталог, используется метод CreateDirectory экземпляра IsolatedStorageFile. Если указывается подкаталог еще не созданного каталога, то создаются оба каталога. Если указывается уже существующий каталог, то исключение не создается. Однако, если указано имя каталога, которое содержит недопустимые знаки, то создается исключение IsolatedStorageException.

Чтобы создать и открыть файл, используйте один из конструкторов IsolatedStorageFileStream, передавая в имени файла значение FileMode OpenOrCreate и хранилище, в котором следует создать файл. После этого можно производить стандартные операции с данными файлового потока, такие как чтение, поиск и запись. Чтобы открыть файл для других целей, также можно использовать конструктор IsolatedStorageFileStream.

Можно создавать или открывать файлы без предварительного получения хранилища при помощи любого из конструкторов IsolatedStorageFileStream, которые не используют аргумент IsolatedStorageFile. При использовании такой формы конструктора, файл создается в домене хранилища файла.

В файловых системах Windows имена каталогов и файлов изолированного хранилища сравниваются без учета регистра. Таким образом, если создать файл с именем ThisFile.txt, а затем создать другой файл с именем THISFILE.TXT, то будет создан только один файл. При отображении сохраняется исходный регистр имени файла.

Пример CreatingFilesAndDirectories

В следующем примере показано, как создавать каталоги и файлы в изолированном хранилище. Сначала извлекается хранилище, изолированное по пользователю, домену и сборке, и помещается в переменную isoStore. Затем для создания нескольких разных каталогов используется метод CreateDirectory, а метод IsolatedStorageFileStream создает несколько файлов в этих каталогах.

Imports System
Imports System.IO
Imports System.IO.IsolatedStorage

Public Class CreatingFilesDirectories
    Public Shared Sub Main()
        ' Get an isolated store for user, domain, and assembly and put it into
        ' an IsolatedStorageFile object.

        Dim isoStore As IsolatedStorageFile
        isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or _
            IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, Nothing, Nothing)

        ' This code creates a few different directories.

        isoStore.CreateDirectory("TopLevelDirectory")
        isoStore.CreateDirectory("TopLevelDirectory/SecondLevel")

        ' This code creates two new directories, one inside the other.

        isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory")

        ' This file is placed in the root.

        Dim isoStream1 As New IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore)
        Console.WriteLine("Created a new file in the root.")
        isoStream1.Close()

        ' This file is placed in the InsideDirectory.

        Dim isoStream2 As New IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", _
            FileMode.Create, isoStore)
        Console.WriteLine("Created a new file in the root.")
        isoStream2.Close()

        Console.WriteLine("Created a new file in the InsideDirectory.")
    End Sub
End Class
using System;
using System.IO;
using System.IO.IsolatedStorage;

public class CreatingFilesDirectories
{
    public static void Main()
    {
        // Get a new isolated store for this user, domain, and assembly.
        // Put the store into an IsolatedStorageFile object.

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
            IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);

        // This code creates a few different directories.

        isoStore.CreateDirectory("TopLevelDirectory");
        isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");

        // This code creates two new directories, one inside the other.
        isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");

        // This file is placed in the root.

        IsolatedStorageFileStream isoStream1 =
            new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
        Console.WriteLine("Created a new file in the root.");
        isoStream1.Close();

        // This file is placed in the InsideDirectory.

        IsolatedStorageFileStream isoStream2 =
            new IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt",
            FileMode.Create, isoStore);
        isoStream2.Close();

        Console.WriteLine("Created a new file in the InsideDirectory.");
    } // End of Main.
}
using namespace System;
using namespace System::IO;
using namespace System::IO::IsolatedStorage;

public ref class CreatingFilesDirectories
{
public:
    static void Main()
    {
        // Get a new isolated store for this user, domain, and assembly.
        // Put the store into an IsolatedStorageFile object.

        IsolatedStorageFile^ isoStore =  IsolatedStorageFile::GetStore( IsolatedStorageScope::User |
            IsolatedStorageScope::Domain | IsolatedStorageScope::Assembly,
            (Type ^)nullptr, (Type ^)nullptr);

        // This code creates a few different directories.

        isoStore->CreateDirectory("TopLevelDirectory");
        isoStore->CreateDirectory("TopLevelDirectory/SecondLevel");

        // This code creates two new directories, one inside the other.

        isoStore->CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");

        // This file is placed in the root.

        IsolatedStorageFileStream^ isoStream1 =
            gcnew IsolatedStorageFileStream("InTheRoot.txt", FileMode::Create, isoStore);
        Console::WriteLine("Created a new file in the root.");
        isoStream1->Close();

        // This file is placed in the InsideDirectory.

        IsolatedStorageFileStream^ isoStream2 =
            gcnew IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt",
            FileMode::Create, isoStore);
        isoStream2->Close();

        Console::WriteLine("Created a new file in the InsideDirectory.");
    } // End of Main.
};

int main()
{
    CreatingFilesDirectories::Main();
}

См. также

Ссылки

IsolatedStorageFile

IsolatedStorageFileStream

Основные понятия

Изолированное хранилище