FileIO在win 8 app中

时间:2012-08-22 11:37:40

标签: c# windows-8

我必须在文件夹

中的win 8 app中的文件中记录我的应用程序事件和异常
Windows.Storage.StorageFolder localFolder = KnownFolders.DocumentsLibrary;

问题是当我一个接一个地调用WriteToFile函数时,存在拒绝访问的异常,因为该文件仍在使用中。 有没有办法让这项工作

public async void WriteToFile(string log)
            {
                try
                {

                    StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.OpenIfExists);
                    //StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
                    IRandomAccessStream writeStream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);
                    IOutputStream outputStream = writeStream.GetOutputStreamAt(writeStream.Size);
                    DataWriter dataWriter = new DataWriter(outputStream);
                    dataWriter.WriteString(log);

                    dataWriter.StoreAsync().AsTask().Wait();
                    outputStream.FlushAsync().AsTask().Wait();

                }
                finally
                {

                }

            }

2 个答案:

答案 0 :(得分:2)

看起来您忘了在写入操作后关闭Stream。 在关闭Stream之前,文件将被锁定。

dataWriter.Close();

MSDN Link

或使用“using”关键字,如下所示:

 using(DataWriter dataWriter = new DataWriter(outputStream)) 
 {
       dataWriter.WriteString(log);
       dataWriter.StoreAsync().AsTask().Wait(); 
 }

检查文件是否已锁定是个好主意,因此您没有得到异常。

How to Check for locked file

问候,希望有所帮助

答案 1 :(得分:0)

您可以尝试以下

dataWriter.Dispose();
await outputStream.FlushAsync();
await stream.FlushAsync();