使用StreamWriter后文件是空白的

本文关键字:空白 文件 StreamWriter 使用 | 更新日期: 2023-09-27 18:08:29

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

        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");
        }

使用StreamWriter后文件是空白的

编辑

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

如果你需要从你的开发机器访问文件,你需要一个实用程序,如Windows Phone Power Tools (c/o Alastair Pitts,上面)或SDK的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");
}