簡體   English   中英

如何覆蓋同一文本文件中的文本

[英]How to overwrite text in same text file

我正在努力使用控制台應用程序覆蓋文本文件並進行一些更改。 在這里,我正在逐行讀取文件。 誰能幫我。

StreamReader sr = new StreamReader(@"C:\abc.txt");
string line;
line = sr.ReadLine();

while (line != null)
{
  if (line.StartsWith("<"))
  {
    if (line.IndexOf('{') == 29)
    {
      string s = line;
      int start = s.IndexOf("{");
      int end = s.IndexOf("}");
      string result = s.Substring(start+1, end - start - 1);
      Guid g= Guid.NewGuid();
      line = line.Replace(result, g.ToString());
      File.WriteAllLines(@"C:\abc.txt", line );
    }
  }
  Console.WriteLine(line);

  line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();

在這里,我得到錯誤文件已經由另一個進程打開

任何人都請幫助我。 主要任務是通過修改覆蓋相同的texfile

您只需要一個流,就可以同時打開它進行讀寫。

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

現在您可以使用fileStream.Read() and fileStream.Write()方法

請參閱此鏈接進行擴展討論

如何在C#中讀取和寫入文件

問題是您正在嘗試寫入StreamReader使用的文件。 你必須將其關閉或-更好-使用using語句來處置其/關閉它甚至錯誤。

using(StreamReader sr = new StreamReader(@"C:\abc.txt"))
{
    // ...
}
File.WriteAllLines(...);

File.WriteAllLines還將所有行不僅寫入當前行,而且在循環中這樣做毫無意義。

我可以建議您使用其他方法來讀取文本文件的行嗎? 您可以使用File.ReadAllLines將所有行讀入string[]File.ReadLines ,其工作方式類似於StreamReader通過延遲讀取所有行。

這是一個版本相同的版本,但是使用(更易讀?)LINQ查詢:

var lines = File.ReadLines(@"C:\abc.txt")
    .Where(l => l.StartsWith("<") && l.IndexOf('{') == 29)
    .Select(l => 
    {
        int start = l.IndexOf("{");
        int end = l.IndexOf("}", start);
        string result = l.Substring(start + 1, end - start - 1);
        Guid g = Guid.NewGuid();
        return l.Replace(result, g.ToString());
    }).ToList();
File.WriteAllLines(@"C:\abc.txt", lines);

問題是您已打開文件並在寫入文件的同時從同一文件讀取。 但是你應該做的是

  1. 從文件中讀取更改
  2. 關閉檔案
  3. 將內容寫回文件

所以你的代碼應該像

List<string> myAppendedList = new List<string>();
using (StreamReader sr = new StreamReader(@"C:\abc.txt"))

{
    string line;
    line = sr.ReadLine();

    while (line != null)
    {
        if (line.StartsWith("<"))
        {
            if (line.IndexOf('{') == 29)
            {
                string s = line;
                int start = s.IndexOf("{");
                int end = s.IndexOf("}");
                string result = s.Substring(start + 1, end - start - 1);
                Guid g = Guid.NewGuid();
                line = line.Replace(result, g.ToString());
                myAppendedList.Add(line);

            }
        }
        Console.WriteLine(line);

        line = sr.ReadLine();
    }
}

if(myAppendedList.Count > 0 )
    File.WriteAllLines(@"C:\abc.txt", myAppendedList);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM