Reputation: 784
I have to log my application events and exceptions in a file in win 8 app in documents folder
Windows.Storage.StorageFolder localFolder = KnownFolders.DocumentsLibrary;
The problem is when I call WriteToFile function one after other there is an access is denied exception because the file is still being used. Is there a way to make this work
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
{
}
}
Upvotes: 1
Views: 1117
Reputation: 2085
you could try the following
dataWriter.Dispose();
await outputStream.FlushAsync();
await stream.FlushAsync();
Upvotes: 0
Reputation: 211
Looks like you forgot to close the Stream after write operation. The file will be locked until you close the Stream.
dataWriter.Close();
or use the "using" Keyword like this:
using(DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteString(log);
dataWriter.StoreAsync().AsTask().Wait();
}
It's a good idea to check if the file is locked, so you didn't get an exception.
Greetings, hope it helps
Upvotes: 2