将标头添加到现有文件

时间:2014-03-07 10:46:12

标签: c#

如何在文本文件中添加现有数据的文本开头。基本上我需要在文本文件中提供此数据之前的标题。此标头是动态数据。

这是我的实际文字

The claim against the Defendant is for a breach of contract in respect of a Parking Charge Notice issued to the vehicle.

要添加的标题是

17383001 followed by space (1983).

这是我的代码

FileStream fs = new FileStream(@"C:\Users\IT-Administrator\Desktop\ee.txt", FileMode.Open, FileAccess.Write);
fs.Seek(0, SeekOrigin.Begin);

StreamWriter sw = new StreamWriter(fs);
//sw.WriteLine(comboBox7.Text +comboBox2.Text +textBox6.Text);
sw.WriteLine("{0}{1}{2}{3,-1983}", comboBox7.Text, comboBox2.Text,textBox6.Text, ' ');
sw.Close();
fs.Close();

2 个答案:

答案 0 :(得分:3)

最简单的是重新创建整个文件:

string header = string.Format("{0}{1}{2}{3,-1983}", comboBox7.Text, comboBox2.Text,textBox6.Text, ' ');
string[] newLines = new[]{ header }.Concat(File.ReadLines(path)).ToArray();
File.WriteAllLines(path, newLines);

更新“我应该有1983年的空白或空白空间”

使用string constructornew string(' ', 1983),所以:

string header = string.Format("{0}{1}{2}{3}"
                 , comboBox7.Text
                 , comboBox2.Text
                 , textBox6.Text
                 , new string(' ', 1983));

答案 1 :(得分:2)

实现目标的最简单方法是使用File.ReadAllTextFile.WriteAllText

string fileText = File.ReadAllText("C:\\file.txt");
fileText = string.Format("{0}{1}.{2}", "17383001", new string(' ', 1983), fileText);
File.WriteAllText("C:\\file.txt", fileText);
相关问题