[英]c# Write a line into a text file at specific line number
我正在網上搜索,但找不到正確的示例。
目標是具有一個功能:
private void InsertLine(string source, string position, string content)
並使用StreamWriter寫入文件,因此您無需讀取所有行,因為該文件可能很大。
到目前為止,我的功能:
private void InsertLine(string source, string position, string content)
{
if (!File.Exists(source))
throw new Exception(String.Format("Source:{0} does not exsists", source));
var pos = GetPosition(position);
int line_number = 0;
string line;
using (var fs = File.Open(source, FileMode.Open, FileAccess.ReadWrite))
{
var destinationReader = new StreamReader(fs);
var writer = new StreamWriter(fs);
while (( line = destinationReader.ReadLine()) != null)
{
if (line_number == pos)
{
writer.WriteLine(content);
break;
}
line_number++;
}
}
}
該功能在文件中不起作用,因為什么也沒有發生。
您不能只在文件中插入一行。 文件是字節序列。
你需要:
這是一些基於您的未經測試的代碼:
private void InsertLine(string source, string position, string content)
{
if (!File.Exists(source))
throw new Exception(String.Format("Source:{0} does not exsists", source));
// I don't know what all of this is for....
var pos = GetPosition(position);
int line_number = 0;
string line;
using (var fs = File.Open(source, FileMode.Open, FileAccess.ReadWrite))
{
var destinationReader = new StreamReader(fs);
var writer = new StreamWriter(fs);
while (( line = destinationReader.ReadLine()) != null)
{
writer.WriteLine(line); // ADDED: You need to write every original line
if (line_number == pos)
{
writer.WriteLine(content);
// REMOVED the break; here. You need to write all following lines
}
line_number++; // MOVED this out of the if {}. Always count lines.
}
}
}
但是,這可能無法正常工作。 您正在嘗試寫入要讀取的文件。 您應該打開一個新的(臨時)文件,執行復制+插入,然后移動/重命名該臨時文件以替換原始文件。
此代碼將幫助您在希望的行號上插入文本
string path ="<Path of file>"
List<string> lines = System.IO.File.ReadAllLines(path).ToList<string>();
//give the line to be inserted
lines[10]="New String";
System.IO.File.WriteAllLines(path, lines);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.