【问题标题】:Rewriting a text file after reading it读取文本文件后重写
【发布时间】:2012-10-17 20:27:09
【问题描述】:

我有一个文件存储在我的应用程序目录中,他有一些站点列表。 我读它没有任何问题,但是当我想写它时,我得到了

System.ArgumentException: Stream is not writeable

这就是我访问文件的方式:

  FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate);

这是让我期待的功能:

public static void WriteNewTextToFile(string text, FileStream theFile)
    {
        string fileText = GetAllTextFromFile(theFile);
        ArrayList fileLIst = populateListFromText(fileText);

        using (StreamWriter fileWriter = new StreamWriter(theFile))
        {
            fileWriter.Write(String.Empty);
            for (int i = 0; i < fileLIst.Count; i++)
            {
                fileWriter.WriteLine(fileLIst[i].ToString());        
            }
        }
    }

该函数读取旧文本和新文本并将其添加到数组中。然后我从所有东西中清理文件,并用我制作的 arry 中的新旧数据重写它。

我不知道这是否会有所帮助,但这是文件属性:

Build Action: None
Copy To Out Put Directory: Copy always

为什么我不能重写文件?

这是我用来读取文件内容的函数:

public static string GetAllTextFromFile(FileStream theFile)
    {
        string fileText = "";

        using (theFile)
        {
            using (StreamReader stream = new StreamReader(theFile))
            {
                string currentLine = "";
                while ((currentLine = stream.ReadLine()) != null)
                {
                    fileText += currentLine + "\n";
                }

            }
        }

        return fileText;

    }

【问题讨论】:

  • 您是否使用与打开文件相同的FileStream
  • 你如何读取文件?
  • 我添加了我用来读取文件的函数。
  • 您确认您的文件名正确吗?! “四连”
  • 顺便说一句,不要相信Environment.CurrentDirectory 会随时为您提供您期望的目录的路径。请改用此方法:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))。取自另一个SO thread

标签: c# text text-files


【解决方案1】:

您必须使用读/写文件访问权限作为third 参数-

FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate, FileAccess.ReadWrite
);

重要 - 删除 using(theFile) 声明:

public static string GetAllTextFromFile(FileStream theFile)
{
        string fileText = "";

        using (StreamReader stream = new StreamReader(theFile))
        {
            string currentLine = "";
            while ((currentLine = stream.ReadLine()) != null)
            {
                fileText += currentLine + "\n";
            }

        }


    return fileText;

}

不要在您的情况下使用 using 构造,因为它会关闭底层流,因为在您的情况下您必须手动 openclose stream 对象。

这也将允许您写入文件。

有关更多信息,请参阅以下链接 -

【讨论】:

  • 仍然不工作,我得到了同样的例外。我在运行时创建的表单中打开文件,这会影响流吗?
  • 我用visual studio添加了文件,我如何使用visual studio查看他是否是只读的?
  • GetAllTextFromFile方法中移除using (theFile)
  • using (StreamReader stream = new StreamReader(theFile)) 也关闭了底层文件流对象msdn.microsoft.com/en-us/library/…
  • 是的,问题是我需要确保流仍然存在,我更改了一些东西,每次我需要做某事时我都会重新打开它。谢谢
猜你喜欢
  • 2013-11-04
  • 2013-12-02
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多