2013-12-20 60 views
1

我在与使用控制台应用程序进行一些更改覆盖文本文件的斗争。在这里我正在逐行阅读文件。谁能帮我。如何覆盖同一个文本文件中的文本

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文件

+0

您应该读取所​​有使用流读取器的行,将它们存储在行集合中,然后在开始写入fi之前关闭流读取器再次。 –

回答

0

你需要一个单一的流, 打开它的阅读和写作。

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

现在你可以使用fileStream.Read() and fileStream.Write()方法

请参阅此链接,进一步讨论

How to both read and write a file in C#

0

的问题是,你要写信给所使用的文件StreamReader。你必须关闭它,或者 - 更好 - 使用using-表示即使出错也能处理/关闭它的语句。

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

File.WriteAllLines也写的所有行到该文件不仅currrent线,所以它是没有意义的做到这一点的循环。

我可以建议你使用不同的方法来读取文本文件的行吗?您可以使用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); 
+0

谢谢蒂姆,它的工作。 – user2477724

0

问题是,你已经打开了文件,并在你在写的同时从同一个文件中读取文件。但是,你应该做的是,

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