我正在寫這個程序,它允許我生成帶增量數字的txt文件,但是,我希望每個文件序列號都在txt文件中寫入本身。打開txt文件並替換前兩行中的文本(C#)
例如:我生成了3個文件Mytext-000001.txt, 000000「,現在我想要更改每個txt文件以包含」Hello「+它所命名的增量編號。
所以每個文件的輸出將是:
Mytext-000001.txt,
Hello 000001
My number is 000001
Mytext-000002.txt,
Hello 000002
My number is 000002
Mytext-000003.txt,
Hello 000002
My number is 000003
我的代碼
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\path.txt";
string pth_input = null;
string pth_output = null;
using (StreamReader sx = File.OpenText(path))
{
pth_input = sx.ReadLine();
pth_output = sx.ReadLine();
}
Console.WriteLine("Number of Files?");
string number_of_files = Console.ReadLine();
int get_number_of_files = Int32.Parse(number_of_files) + 1;
string PathFiletoCopy = pth_input;
string Extension = System.IO.Path.GetExtension(PathFiletoCopy);
string PartialNewPathFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(PathFiletoCopy), System.IO.Path.GetFileNameWithoutExtension(PathFiletoCopy) + "-");
for (int i = 1; i < get_number_of_files; i++)
{
System.IO.File.Copy(PathFiletoCopy, PartialNewPathFile + i.ToString("D6") + Extension);
}
string[] txtfiles = Directory.GetFiles(pth_output, "*.txt");
foreach (var file in txtfiles)
{
string get_file_counter = System.IO.Path.GetDirectoryName(file.Substring(7,6));
FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write);
FileStream fi = new FileStream(file, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fi))
{
using (StreamWriter writer = new StreamWriter(fs))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
string replace_line_one = line.Replace("Hello 000001","Hello"+ "["+get_file_counter+"]");
string replace_line_two = line.Replace("My number is 000001", "My number is" + "[" + get_file_counter + "]");
}
writer.Close();
} reader.Close();
}
}
Console.Read();
我希望你能幫助
感謝您的幫助球員
看起來你已經有一些代碼試圖做到這一點。什麼是實際問題?您需要讚揚您的代碼發佈,但是問題是什麼? –
嘿,我得到的錯誤是,不能訪問該文件,因爲它正在被另一個進程使用。 – user1848210
'FileReadAllLines()';然後根據需要更換; 'FileWriteAllLines()' – Plutonix