<UWP> 文件操作StorageFile 避免Unable to remove the file to be replaced

UWP文件操件
  1. 使用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)
{
  // ...
}
  1. 使用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值