파일 만들기, 쓰기 및 읽기

[ Windows 10의 UWP 앱에 맞게 업데이트되었습니다. Windows 8.x 문서는 보관을 참조하세요. ]

중요 API

StorageFile 개체를 사용하여 파일을 읽고 씁니다.

참고

파일 액세스 샘플도 참조하세요.

필수 조건

파일 만들기

앱의 로컬 폴더에 파일을 만드는 방법은 다음과 같습니다. 이미 있는 경우 바꿉니다.

C#
// Create sample file; replace if exists.
Windows.Storage.StorageFolder storageFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
    await storageFolder.CreateFileAsync("sample.txt",
        Windows.Storage.CreationCollisionOption.ReplaceExisting);
C++
// Create a sample file; replace if exists.
StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
concurrency::create_task(storageFolder->CreateFileAsync("sample.txt", CreationCollisionOption::ReplaceExisting));
VB
' Create sample file; replace if exists.
Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting)

파일에 쓰기

StorageFile 클래스를 사용하여 디스크의 쓰기 가능 파일에 쓰는 방법은 다음과 같습니다. 파일에 쓰는 각 방법의 공통적인 첫 번째 단계(파일을 만든 즉시 해당 파일에 쓰는 경우 제외)는 StorageFolder.GetFileAsync를 사용하여 파일을 가져오는 것입니다.

C#
Windows.Storage.StorageFolder storageFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
    await storageFolder.GetFileAsync("sample.txt");
C++
StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile) 
{
    // Process file
});
VB
Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync("sample.txt")

파일에 텍스트 쓰기

FileIO 클래스의 WriteTextAsync 메서드를 호출하여 파일에 텍스트를 씁니다.

C#
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");
C++
StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile) 
{
    //Write text to a file
    create_task(FileIO::WriteTextAsync(sampleFile, "Swift as a shadow"));
});
VB
Await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow")

버퍼를 사용하여 파일에 바이트 쓰기(2단계)

  1. 먼저 ConvertStringToBinary를 호출하여 파일에 쓰려는 바이트(임의 문자열 기반)의 버퍼를 가져옵니다.

    C#
    var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(
            "What fools these mortals be", Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        // Create the buffer
        IBuffer^ buffer = CryptographicBuffer::ConvertStringToBinary
        ("What fools these mortals be", BinaryStringEncoding::Utf8);
    });
    
    VB
    Dim buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(
                        "What fools these mortals be",
                        Windows.Security.Cryptography.BinaryStringEncoding.Utf8)
    
  2. 그런 다음 FileIO 클래스의 WriteBufferAsync 메서드를 호출하여 파일에 버퍼의 바이트를 씁니다.

    C#
    await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        // Create the buffer
        IBuffer^ buffer = CryptographicBuffer::ConvertStringToBinary
        ("What fools these mortals be", BinaryStringEncoding::Utf8);      
        // Write bytes to a file using a buffer
        create_task(FileIO::WriteBufferAsync(sampleFile, buffer));
    });
    
    VB
    Await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer)
    

스트림을 사용하여 파일에 텍스트 쓰기(4단계)

  1. 먼저 StorageFile.OpenAsync 메서드를 호출하여 파일을 엽니다. 이 메서드는 열기 작업이 완료되면 파일 내용의 스트림을 반환합니다.

    C#
    var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        create_task(sampleFile->OpenAsync(FileAccessMode::ReadWrite)).then([sampleFile](IRandomAccessStream^ stream)
        {
            // Process stream
        });
    });
    
    VB
    Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)
    
  2. 다음으로, stream에서 GetOutputStreamAt 메서드를 호출하여 출력 스트림을 가져옵니다. using 문에 이 스트림을 넣어 출력 스트림의 수명을 관리합니다.

    C#
    using (var outputStream = stream.GetOutputStreamAt(0))
    {
        // We'll add more code here in the next step.
    }
    stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
    
    C++
    // Add to "Process stream" in part 1
    IOutputStream^ outputStream = stream->GetOutputStreamAt(0);
    
    VB
    Using outputStream = stream.GetOutputStreamAt(0)
    ' We'll add more code here in the next step.
    End Using
    
  3. 이제 기존 using 문 내에 다음 코드를 추가해 새 DataWriter 개체를 만들고 DataWriter.WriteString 메서드를 호출하여 출력 스트림에 씁니다.

    C#
    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
    {
        dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.");
    }
    
    C++
    // Added after code from part 2
    DataWriter^ dataWriter = ref new DataWriter(outputStream);
    dataWriter->WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.");
    
    VB
    Dim dataWriter As New DataWriter(outputStream)
    dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.")
    
  4. 마지막으로, 내부 using 문 내에 다음 코드를 추가하여 StoreAsync로 텍스트를 파일에 저장하고 FlushAsync로 스트림을 닫습니다.

    C#
    await dataWriter.StoreAsync();
        await outputStream.FlushAsync();
    
    C++
    // Added after code from part 3
    dataWriter->StoreAsync();
    outputStream->FlushAsync();
    
    VB
    Await dataWriter.StoreAsync()
        Await outputStream.FlushAsync()
    

파일에서 읽기

StorageFile 클래스를 사용하여 디스크의 파일에서 읽는 방법은 다음과 같습니다. 파일에서 읽는 각 방법의 공통적인 첫 번째 단계는 StorageFolder.GetFileAsync를 사용하여 파일을 가져오는 것입니다.

C#
Windows.Storage.StorageFolder storageFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
    await storageFolder.GetFileAsync("sample.txt");
C++
StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
{
    // Process file
});
VB
Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync("sample.txt")

파일에서 텍스트 읽기

FileIO 클래스의 ReadTextAsync 메서드를 호출하여 파일에서 텍스트를 읽습니다.

C#
string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
C++
StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
{
    return FileIO::ReadTextAsync(sampleFile);
});
VB
Dim text As String = Await Windows.Storage.FileIO.ReadTextAsync(sampleFile)

버퍼를 사용하여 파일에서 텍스트 읽기(2단계)

  1. 먼저 FileIO 클래스의 ReadBufferAsync 메서드를 호출합니다.

    C#
    var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        return FileIO::ReadBufferAsync(sampleFile);
    
    }).then([](Streams::IBuffer^ buffer)
    {
        // Process buffer
    });
    
    VB
    Dim buffer = Await Windows.Storage.FileIO.ReadBufferAsync(sampleFile)
    
  2. 그런 다음 DataReader 개체를 사용하여 버퍼의 길이와 버퍼의 내용을 차례로 읽습니다.

    C#
    using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
    {
        string text = dataReader.ReadString(buffer.Length);
    }
    
    C++
    // Add to "Process buffer" section from part 1
    auto dataReader = DataReader::FromBuffer(buffer);
    String^ bufferText = dataReader->ReadString(buffer->Length);
    
    VB
    Dim dataReader As DataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)
    Dim text As String = dataReader.ReadString(buffer.Length)
    

스트림을 사용하여 파일에서 텍스트 읽기(4단계)

  1. StorageFile.OpenAsync 메서드를 호출하여 파일의 스트림을 엽니다. 이 메서드는 작업이 완료되면 파일 내용의 스트림을 반환합니다.

    C#
    var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        create_task(sampleFile->OpenAsync(FileAccessMode::Read)).then([sampleFile](IRandomAccessStream^ stream)
        {
            // Process stream
        });
    });
    
    VB
    Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read)
    
  2. 나중에 사용할 스트림의 크기를 가져옵니다.

    C#
    ulong size = stream.Size;
    
    C++
    // Add to "Process stream" from part 1
    UINT64 size = stream->Size;
    
    VB
    Dim size = stream.Size
    
  3. GetInputStreamAt 메서드를 호출하여 입력 스트림을 가져옵니다. 이를 using 문에 배치하여 스트림의 수명을 관리합니다. GetInputStreamAt을 호출할 때 0을 지정하여 위치를 스트림의 시작 부분으로 설정합니다.

    C#
    using (var inputStream = stream.GetInputStreamAt(0))
    {
        // We'll add more code here in the next step.
    }
    
    C++
    // Add after code from part 2
    IInputStream^ inputStream = stream->GetInputStreamAt(0);
    auto dataReader = ref new DataReader(inputStream);
    
    VB
    Using inputStream = stream.GetInputStreamAt(0)
        ' We'll add more code here in the next step.
    End Using
    
  4. 마지막으로, 기존 using 문 내에 다음 코드를 추가하여 스트림에서 DataReader 개체를 가져온 다음 DataReader.LoadAsync  DataReader.ReadString를 호출하여 텍스트를 읽습니다.

    C#
    using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
    {
        uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
        string text = dataReader.ReadString(numBytesLoaded);
    }
    
    C++
    // Add after code from part 3
    create_task(dataReader->LoadAsync(size)).then([sampleFile, dataReader](unsigned int numBytesLoaded)
    {
        String^ streamText = dataReader->ReadString(numBytesLoaded);
    });
    
    VB
    Dim dataReader As New DataReader(inputStream)
    Dim numBytesLoaded As UInteger = Await dataReader.LoadAsync(CUInt(size))
    Dim text As String = dataReader.ReadString(numBytesLoaded)


+ Recent posts