0

テキストファイルの行を1つ上に移動してから元のファイルに書き直そうとしていますが、何らかの理由でエラーが発生し、理解できないようです。

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++;
}
4

5 に答える 5

5

次の行で読み取るファイルを開いています。

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

この時点で、それは開いていて使用されています。

その後、次のようになります。

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

同じファイルから読み込もうとしています。

何を達成しようとしているのかは明確ではありませんが、これは機能しません。

私が見ることができることから、あなたはまったく必要ありませんreader

于 2012-05-02T10:30:09.143 に答える
0

ファイルを開いて書き込もうとしている場所は、すでにstreamreaderを使用して開いているメソッド内にあり、ストリームリーダーがファイルを開き、ファイルライターがファイルを開こうとしますが、既に開いているためできません。

于 2012-05-02T10:30:54.247 に答える
0

ファイルの読み取りと書き込みを同時に行わないでください。1。ファイルが小さい場合は、ファイルをロードして変更し、書き戻します。2.ファイルが巨大な場合は、出力用に別の一時ファイルを開き、最初のファイルを削除/削除してから、2番目のファイルの名前を変更します。

于 2012-05-02T10:32:51.843 に答える
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つのプロセスのみを使用してファイルから読み取ります。すべての行を読み取り、破棄して閉じます。

お役に立てれば!

于 2012-05-02T10:36:11.357 に答える
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);

編集:これがあなたの要件であるとコメントしたので、これは前の行と1行だけを交換するわずかに変更されたバージョンです:

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);
于 2012-05-02T10:39:02.290 に答える