0

プロジェクトに2つのテキストファイルを書き込んでいます。1つは入力用、もう1つは出力用です。最後に、両方の同じテキストファイルに書き込む必要があります。

これまでの私のコードは次のとおりです。

static void Main( string[] args )
    {
        string line = null;
        string line_to_delete = "--";
        string desktopLocation = Environment.GetFolderPath( Environment.SpecialFolder.Desktop );
        string text = Path.Combine( desktopLocation, "tim3.txt" );
        string file = Path.Combine( desktopLocation, "tim4.txt" );

        using (StreamReader reader = new StreamReader( text ))
        {
            using (StreamWriter writer = new StreamWriter( file ))
            {
                while (( line = reader.ReadLine() ) != null)
                {
                    if (string.Compare( line, line_to_delete ) == 0)
                        File.WriteAllText( file, File.ReadAllText( text ).Replace( line_to_delete, "" ) );
                    continue;
                }
            }

ありがとう

4

1 に答える 1

3

入力ファイルからすべての行を読み取り、特定のテキストに一致する行を除いて、すべてを出力ファイルに書き込む場合は、次のようにします。

public static void StripUnwantedLines(
    string inputFilePath,
    string outputFilePath,
    string lineToRemove)
{
    using (StreamReader reader = new StreamReader(inputFilePath))
    using (StreamWriter writer = new StreamWriter(outputFilePath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            bool isUnwanted = String.Equals(line, lineToRemove,
                StringComparison.CurrentCultureIgnoreCase);

            if (!isUnwanted)
                writer.WriteLine(line);
        }
    }
}

この場合、比較は現在のカルチャを使用して行われ(「-」を検索する必要がある場合は重要ではないかもしれませんが、指定するのは明らかです)、大文字と小文字は区別されません。指定されたテキストで始まるすべての行をスキップする場合は、で変更する
必要があります。String.Equalsline.StartsWith

この入力ファイルが与えられた場合:

これがファイルの始まりです
- 
テキストの行
- 
別のテキスト行

次の出力が生成されます。

これがファイルの始まりです
テキストの行
別のテキスト行

この例では、ループ
内で次のコードを使用しました。while

File.WriteAllText(file, 
    File.ReadAllText(text).Replace(line_to_delete, ""));

他に何もなければ十分かもしれません(ただし、不要な行が削除され、空の行に置き換えられます)。その問題(空の行を保持することが問題ではない場合)は、ファイル全体をメモリに読み取ることであり、ファイルが本当に大きい場合は(非常に)遅くなる可能性があります。参考までに、これは同じタスクを実行するように書き直す方法です(メモリ内で機能するため、ファイルが大きすぎないようにするため)。

File.WriteAllText(outputFilePath, File.ReadAllText(inputFilePath).
    Where(x => !String.Equals(x, lineToDelete));
于 2012-05-16T12:26:51.567 に答える