UWP文件操件
- 使用StorageFile
System.DateTime currentTime = System.DateTime.Now;
string filename = currentTime.ToString("yyyyMMdd_HHmmss") + "_test.log";
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
// Access Document
storageFolder = storageFolder = KnownFolders.DocumentsLibrary;
LogFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
采用如下写操作可能造成错误:
// write operation
try
{
if (LogFile != null)
{
await FileIO.AppendTextAsync(LogFile, text);
}
}
catch (Exception e)
{
// ...
}
System.Exception: ‘Unable to remove the file to be replaced. (Exception from HRESULT: 0x80070497)’
解决办法采用Stream:
StreamWriter StorageLogSw;
Stream stm = await LogFile.OpenStreamForWriteAsync();
StorageLogSw = new StreamWriter(stm);
// write operation
try
{
if (LogFile != null)
{
StorageLogSw.WriteLine(text);
StorageLogSw.WriteLine("");
StorageLogSw.Flush();
}
}
catch (Exception e)
{
// ...
}
- 使用FileStream
FileStream LogFs;
StreamWriter LogSw;
string path = ApplicationData.Current.LocalFolder.Path + "\\" + filename;
try
{
LogFs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
LogSw = new StreamWriter(LogFs);
}
catch (Exception e)
{
OutputField.Text = "Error: " + e.ToString();
rootPage.NotifyUser("Error: " + e.ToString(), NotifyType.ErrorMessage);
}
// write operation
try
{
if (LogSw != null)
{
LogSw.WriteLine(text);
LogSw.WriteLine("");
LogSw.Flush();
}
}
catch (Exception e)
{
// ...
}
APP访问Document文件夹
Package.appxmanifest添加Capbilities:
<Capabilities>
<uap:Capability Name="documentsLibrary" />
</Capabilities>
Package.appxmanifest添加Extensions:
<Applications>
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="YouApp.App">
<Extensions>
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name=".txt">
<uap:DisplayName>TestLogFile</uap:DisplayName>
<uap:SupportedFileTypes>
<uap:FileType ContentType="filedata/data">.txt</uap:FileType>
<uap:FileType ContentType="filedata/data">.log</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>
</Extensions>
</Application>
</Applications>