gpt4 book ai didi

c# - 使用 StreamWriter 后文件为空

转载 作者:行者123 更新时间:2023-12-03 22:18:32 25 4
gpt4 key购买 nike

我正在尝试将一些数据写入项目中的现有文件(项目的本地文件)。我使用了以下代码

        Uri path = new Uri(@"Notes.txt", UriKind.Relative);

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{

using (StreamWriter writefile = new StreamWriter(new IsolatedStorageFileStream(path.ToString(), FileMode.Append, FileAccess.Write,myIsolatedStorage)))
{
writefile.WriteLine("hi");
writefile.Flush();
writefile.Dispose();
}
}

执行程序时没有异常/错误。但是文件是空白的,不包含任何数据。

我已将文件的构建操作设置为“资源”,将内容设置为“如果更新则复制”。只是为了检查,我删除了文件并进行了测试,它仍然没有给出任何异常,尽管我试图在追加模式下打开。

编辑:我在我的开发环境中打开文件进行检查。但是我后来使用 ISETool.exe 来检查文件。但是根本没有创建文件!这是我使用的更新代码:

 Uri path = new Uri(@"Notes.txt", UriKind.Relative);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(path.ToString(), FileMode.OpenOrCreate, FileAccess.Write, myIsolatedStorage))
using (var writefile = new StreamWriter(stream))
{
writefile.WriteLine("hi");
}

最佳答案

编辑

根据您上面的评论,我认为您的问题实际上是您误解了独立存储的工作原理;它在您的手机模拟器图像中存储文件,这两者都不是您的开发机器的 native 文件系统。

如果您需要从您的开发机器访问该文件,您将需要一个类似 Windows Phone Power Tools 的实用程序(转交 Alastair Pitts ,上文)或 the SDK's isetool.exe如果您不介意命令行界面。

原帖

有两件事让我大吃一惊:

  1. 您没有处置您的IsolatedStorageFileStream
  2. 您应该从 IsolatedStorageFile
  3. 获取您的 IsolatedStorageFileStream 实例
  4. 您不需要在 writefile 上调用 Dispose(这就是 using 所做的)

试试这个:

using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = isolatedStorage.OpenFile(path.ToString(), FileMode.Append, FileAccess.Write))
using (var writefile = new StreamWriter(stream))
{
writefile.WriteLine("hi");
}

关于c# - 使用 StreamWriter 后文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com