2014-03-07 35 views
1

如何在文本文件中添加文本開頭的現有數據。基本上我需要在文本文件中的這些數據之前提供一個標題。這個頭是一個動態數據。將標題添加到現有文件

這是我的實際文本

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(); 
+0

請不要包含inf關於在問題標題中使用的語言的形容詞,除非在沒有它的情況下沒有意義。標籤用於此目的。 –

回答

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); 

更新 「我應該lenght的空白或空的空間,1983年的」

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

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

感謝您的回覆Tim,但標題是動態的。我得到他們的comboBox7.Text,comboBox2.Text,textBox6.Text和我需要一個填充(1983) – preethi

+0

我應該有空白或空白的長度1983 – preethi

+0

@preethi:使用字符串構造函數,我編輯過我的答案。 –

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);