在Xamarin Cross Platform App Development中创建文件

时间:2018-01-03 05:52:04

标签: xamarin.forms uwp

我是Xamarin的新手。我正在尝试使用代码

创建文件
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(DateTime.UtcNow);
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}

上面的代码示例给出了例外情况 System.UnauthorizedAccessException :'访问路径' C:\ Users \ hchittora \ Documents \ myfile.txt'被拒绝。'

这是完整的堆栈跟踪

    System.UnauthorizedAccessException
    HResult=0x80070005
    Message=Access to the path 'C:\Users\hchittora\Documents\myfile.txt' is denied.
  Source=System.Private.CoreLib
  StackTrace
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.StreamWriter..ctor(String path, Boolean append)
   at FileHandlingSampleApplication.MainPage..ctor() in C:\Users\hchittora\Desktop\FileHandlingSampleApplication\FileHandlingSampleApplication\FileHandlingSampleApplication\MainPage.xaml.cs:line 19
   at FileHandlingSampleApplication.App..ctor() in C:\Users\hchittora\Desktop\FileHandlingSampleApplication\FileHandlingSampleApplication\FileHandlingSampleApplication\App.xaml.cs:line 16
   at FileHandlingSampleApplication.UWP.MainPage..ctor() in C:\Users\hchittora\Desktop\FileHandlingSampleApplication\FileHandlingSampleApplication\FileHandlingSampleApplication.UWP\MainPage.xaml.cs:line 24
   at FileHandlingSampleApplication.UWP.FileHandlingSampleApplication_UWP_XamlTypeInfo.XamlTypeInfoProvider.Activate_4_MainPage() in C:\Users\hchittora\Desktop\FileHandlingSampleApplication\FileHandlingSampleApplication\FileHandlingSampleApplication.UWP\obj\x86\Debug\XamlTypeInfo.g.cs:line 255
   at FileHandlingSampleApplication.UWP.FileHandlingSampleApplication_UWP_XamlTypeInfo.XamlUserType.ActivateInstance() in C:\Users\hchittora\Desktop\FileHandlingSampleApplication\FileHandlingSampleApplication\FileHandlingSampleApplication.UWP\obj\x86\Debug\XamlTypeInfo.g.cs:line 476

当我查看上述问题时,我才知道UWP无法直接与系统文件进行交互。这样做的另一种选择是什么?

2 个答案:

答案 0 :(得分:0)

由于Xamarin.Forms在多个平台上运行,每个平台都有自己的文件系统,因此没有一种方法可以加载和保存用户创建的文件。

我无法在此为所有平台提供代码,因为您需要了解它的基础。查看this了解更多详情。

答案 1 :(得分:0)

我正在使用带有依赖注入的SecureStorage库来保存每个平台。虽然这主要用于令牌缓存,但您可能会发现它很有用。