[英]Add header to an existing file
How to add text beginning of the existing data in a text file. 如何在文本文件中的现有数据的开头添加文本。 Basically i need to provide a header before this data in a text file.
基本上,我需要在文本文件中的此数据之前提供标题。 This header is a dynamic data.
该头是动态数据。
this is my actual text 这是我的实际文字
The claim against the Defendant is for a breach of contract in respect of a Parking Charge Notice issued to the vehicle.
header to add is 标头添加为
17383001 followed by space (1983).
this is my code 这是我的代码
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();
The simplest is to recreate the whole file: 最简单的是重新创建整个文件:
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);
Update "i should have blank or empty space of lenght 1983" 更新 “我应该有长度为1983的空白或空白空间”
Use the string constructor : new string(' ', 1983)
, so: 使用字符串构造函数 :
new string(' ', 1983)
,所以:
string header = string.Format("{0}{1}{2}{3}"
, comboBox7.Text
, comboBox2.Text
, textBox6.Text
, new string(' ', 1983));
The easiest way to achieve what you want is to use File.ReadAllText and File.WriteAllText : 实现所需目标的最简单方法是使用File.ReadAllText和File.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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.