如何在Windows运行时将流写入文件?

时间:2014-05-17 16:08:18

标签: c# windows-phone-8 windows-runtime windows-store-apps windows-phone-8.1

有很多问题,但主要是关于将字符串写入文件。我有点困惑!

将流写入文件的正确方法是什么?

我做了什么:

Stream stream = await GetStream(source);

var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("TempUsersFile", CreationCollisionOption.ReplaceExisting);
var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

using (var dataWriter = new Windows.Storage.Streams.DataWriter(fileStream))
{
    // How can I write to buffer and write to the file
}

2 个答案:

答案 0 :(得分:1)

我建议使用StreamReader和StreamWriter类:

 StreamWriter sw = new StreamWriter(outstream);
 StreamReader sr = new StreamReader(instream);

 while (!sr.EndOfStream)
 {
    int ch = sr.Read();
    sw.Write(ch);
 }

答案 1 :(得分:1)

有很多方法可以将流写入文件,它们也取决于您的需求。下面的方法使用指定的缓冲区执行异步操作:

public async Task SaveStreamToFile(Stream streamToSave, string fileName, CancellationToken cancelToken)
{
    StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    using (Stream fileStram = await file.OpenStreamForWriteAsync())
    {
        const int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];

        int bytesread = 0;
        while ((bytesread = await streamToSave.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
        {
            await fileStram.WriteAsync(buf, 0, bytesread);
            cancelToken.ThrowIfCancellationRequested();
        }
    }
}

我已经实现了CancellationToken,以防需要取消长时间运行的任务。