I am writing to a file, then reading it back right after:
await FileIO.WriteTextAsync(file, command, Windows.Storage.Streams.UnicodeEncoding.Utf8);
var readFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(WEB_LOG);
However, GetFileAsync
throws a FileNotFoundException
because the file hasn't appeared yet. If I use the debugger and wait a little after WriteTextAsync
finishes, I can see the file appear in the folder and GetFileAsync
does not throw an exception. How can I wait for the file to be fully written to and appear in the folder so that GetFileAsync
does not throw an exception?
CodePudding user response:
You could try to use StorageFolder.TryGetItemAsync(String) to check if the file is ready. This method returns null instead of raising a FileNotFoundException if the specified file or folder is not found.
Like this:
var target= await ApplicationData.Current.TemporaryFolder.TryGetItemAsync("FileName");
if (target != null)
{
// file is ready
}
else
{
//wait and try to get the file again
}
CodePudding user response:
There is no function, which will allow you to wait on a particular file to be available for reading. You have to check if it is not ready then wait...
await FileIO.WriteTextAsync(file, command, Windows.Storage.Streams.UnicodeEncoding.Utf8);
while (true)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
if (inputStream.Length > 0)
break;
}
catch (Exception)
{
await Task.Delay(50);
}
}
var readFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(WEB_LOG);