2012-05-02 37 views
0

我想在一个文本文件中向上移动一行,然后将其重写回原始文件,但由于某种原因获取错误,无法似乎弄明白了。该进程无法访问该文件,因为它正在使用(错误)

using (StreamReader reader = new StreamReader("file.txt")) 
{ 
    string line; 
    int Counter = 0; 

    while ((line = reader.ReadLine()) != null) 
    { 
     string filepath = "file.txt"; 
     int i = 5; 
     string[] lines = File.ReadAllLines(filepath); 

     if (lines.Length >= i) 
     { 
      string tmp = lines[i]; 
      lines[i] = lines[i-1]; 
      lines[i-1] = tmp; 
      File.WriteAllLines(filepath, lines); 
     } 
    } 
    Counter++; 
} 
+3

嗯..我认为你在这里做的有点疯狂......这个问题是你正在试图写入一个你已经在StreamReader中打开的文件。你明确想要做什么?也许我们可以帮助你解决你的问题。 –

+0

可能会将所有文件内容存储在数组或列表中。移动它们,然后将整个东西存回..没有while循环 –

+0

你想交换文件中的每一行吗? –

回答

0

我假设你真的想交换,因为此代码段的每一行的文件中,:

string tmp = lines[i]; 
lines[i] = lines[i-1]; 
lines[i-1] = tmp; 

因此,这里的做法应该工作:

String[] lines = System.IO.File.ReadAllLines(path); 
List<String> result = new List<String>(); 
for (int l = 0; l < lines.Length; l++) 
{ 
    String thisLine = lines[l]; 
    String nextLine = lines.Length > l+1 ? lines[l + 1] : null; 
    if (nextLine == null) 
    { 
     result.Add(thisLine); 
    } 
    else 
    { 
     result.Add(nextLine); 
     result.Add(thisLine); 
     l++; 
    } 
} 
System.IO.File.WriteAllLines(path, result); 

(?)编辑:这是稍微修改过的版本,它只用一行代替上一行,因为您已经评论过这是您的要求:

String[] lines = System.IO.File.ReadAllLines(path); 
List<String> result = new List<String>(); 
int swapIndex = 5; 
if (swapIndex < lines.Length && swapIndex > 0) 
{ 
    for (int l = 0; l < lines.Length; l++) 
    { 
     String thisLine = lines[l]; 
     if (swapIndex == l + 1) // next line must be swapped with this 
     { 
      String nextLine = lines[l + 1]; 
      result.Add(nextLine); 
      result.Add(thisLine); 
      l++; 
     } 
     else 
     { 
      result.Add(thisLine); 
     } 
    } 
} 
System.IO.File.WriteAllLines(path, result); 
+0

感谢您现在解决它 – user1285872

5

您打开的文件在这行改为:

using (StreamReader reader = new StreamReader("file.txt")) 

在这一点上是开放的,被使用。

你的话,以后有:

string[] lines = File.ReadAllLines(filepath); 

试图从同一文件中读取。

目前尚不清楚你试图达到什么目标,但这是行不通的。

从我所看到的,你根本不需要reader

0

当你试图打开该文件中写入这是一个方法,多数民众赞成内部已经在使用一个StreamReader打开它,流读取器打开它,文件作家试图打开它,但不能因为它已经打开,

0

不要同时读取和写入文件 1.如果文件很小,只需加载,更改并回写。 2.如果文件很大,只需打开另一个临时文件输出, 删除/删除第一个文件,然后重命名第二个文件。

0

而是具有:

using (StreamReader reader = new StreamReader("file.txt")) 
{ 
... 
string[] lines = File.ReadAllLines(filepath); 
} 

用途:

using (StreamReader reader = new StreamReader("file.txt")) 
{ 
string line; 
string[] lines = new string[20]; // 20 is the amount of lines 
int counter = 0; 
while((line=reader.ReadLine())!=null) 
{ 
    lines[counter] = line; 
    counter++; 
} 
} 

这会从文件中读取所有行,并把它们放到 '行'。

您可以对代码的写入部分执行相同的操作,但是这种方式仅使用1个进程从文件读取。它将读取所有行,然后处理并关闭。

希望这有助于!

相关问题