c# - 可以使用传统的 File.CreateText(path) 代替 IsolatedStorageFile 吗?

标签 c# windows-phone-8 windows-phone-8.1

似乎每个人都假设您必须在 Windows Phone 8 上使用独立存储,但我还没有找到原因。我还使用了一些我正在移植的代码,传统的 File.CreateText(Windows.ApplicationModel.Package.Current.InstalledLocation) 似乎工作正常。

所以在代码中,每个人似乎都在做 this (from developer.nokia.com) :

IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("TestFile.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(textBox1.Text);
Writer.Close();

这实际上非常温顺。我看过太多使 async 的初学者教程,但无法弄清楚原因。然而,上述代码是在 WP7 上下文中呈现的。


更新:虽然以下代码在从 Visual Studio 运行时适用于 WP8 (HTC 8XT) 和 WP8.1 (Lumia 640),但当我部署到商店时,它立即爆炸了试图保存到文件。


下面的代码似乎也能正常工作,至少在 WP 模拟器、运行 Windows Phone 8 的 HTC 8XT 和运行 WP 8.1 的 Lumia 640 上是这样。可以在稍微好一点的上下文中看到下面的代码 at this link ,但这是重要的东西。是的,我正在使用一些匈牙利语。对不起。显然,您的页面需要有一个名为 txtText 的文本框和一个名为 strFileLoc 的全局文本框。

Windows.ApplicationModel.Package package =
    Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = 
    package.InstalledLocation;
this.strFileLoc = Path.Combine(installedLocation.Path, 
    "myFile.txt");

string strToWrite = this.txtText.Text;
using (StreamWriter sw = File.CreateText(this.strFileLoc))
{
    sw.WriteLine(strToWrite);
    sw.Close();
}

// Load
string strText = string.Empty;
if (File.Exists(this.strFileLoc))
{
    using (StreamReader sr = 
        new StreamReader(File.OpenRead(this.strFileLoc)))
    {
        strText = sr.ReadToEnd();
    }
}
else
{
    strText = "File doesn't exist";
}
this.txtText.Text = strText;

这可以用在生产应用中吗?为什么或为什么不?

最佳答案

由于基于 VS 的部署为您的应用程序提供了对安装位置的写访问权限(一个烦人的错误/设计问题),因此代码在调试时可以正常工作。当您的应用程序从商店部署时,它没有安装位置的权限并且会崩溃。解决方案是不要尝试在安装文件夹中创建(或写入)文件;使用你的一个 ApplicationData folders相反。

至于使用同步方法还是异步方法,有两个答案。第一个答案是,假设您从 UI 线程进行调用,异步方法允许您的 UI 保持响应,即使 I/O 需要很长时间(例如,从 SD 卡加载时可能会这样做)。依赖同步 API 意味着您的 UI 可能会出现故障或看起来已经崩溃。

第二个答案是 System.IO API 对跨 Windows 8/8.1 的通用应用程序无效,因此如果您想重复使用代码,您别无选择,只能使用 ...异步 WinRT API。

从 Windows 10 通用应用开始,您可以在所有 Windows 设备系列中再次使用 System.IO.File。由于您可以设置当前目录,您可以做这样的事情:

Directory.SetCurrentDirectory(ApplicationData.Current.LocalFolder.Path);
using (var f = File.CreateText("hello.txt"))
{
  f.WriteLine("Hello, world");
}

注意当前目录是一个进程范围的设置,所以一般要避免这种代码(在不同的线程中设置不同的值只会导致泪流满面),但它很有用如果您有依赖于相对路径的现有代码。另请注意,理想情况下,您只会在后台线程中运行上述代码,因为这可能需要一些时间才能完成。

关于c# - 可以使用传统的 File.CreateText(path) 代替 IsolatedStorageFile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517734/

相关文章:

c# - 如何在 CaptureElement 中旋转相机 View ?

c# - VS 2010 SP1 - 此安装不支持项目类型

c# - 如何使用7z SDK压缩和解压XZ文件

c# - WPF 包装面板中的 float 行为

javascript - 在 Windows Phone 8 上的 IE10 中查找屏幕分辨率

windows-phone-7 - 在 Windows Phone 8 上测试 .xap,无需注册

c# - 如何在 VS 2013 中调试 Windows Phone (8) 运行时组件或 C++ DLL 中的 C++ 代码

c# - 如何在 Windows Phone 8.1 中添加共享命令栏

windows-phone-8 - 单击 "tools"时 Windows Phone 8.1 模拟器 Xde.exe 停止工作

c# - 更改 JSON 文件中的值(写入文件)