我知道這已被問了幾次,但我需要一種快速方式在具有不同大小(小文件和大文件)的文件中執行此操作。在特定行中編輯特定單詞
我需要在sat(txt)文件中編輯比例因子。這是在第三行中的第一數量:
700 104 1 0 16的Autodesk的AutoCAD 19 ASM 221.0.0.1871 NT 24週二
年08月16 9時02分14秒2016
9.9999999999999995 E-007 1E-010
我知道這已被問了幾次,但我需要一種快速方式在具有不同大小(小文件和大文件)的文件中執行此操作。在特定行中編輯特定單詞
我需要在sat(txt)文件中編輯比例因子。這是在第三行中的第一數量:
700 104 1 0 16的Autodesk的AutoCAD 19 ASM 221.0.0.1871 NT 24週二
年08月16 9時02分14秒2016
9.9999999999999995 E-007 1E-010
我建議提取方法和LINQ:
private static String MyEditLine(string value) {
var items = value.Split(new char[] { ' ' }, 2);
items[0] = "2000"; // let's change 1000 into 2000
return string.Join(" ", items);
}
...
var target = File
.ReadLines(@"C:\MyFile.txt")
.Select((line, index) => index != 2
? line
: MyEditLine(line))
.ToList();
File.WriteAllLines(@"C:\MyFile.txt", target);
謝謝。這對我有用。 –
但是,這種方法將整個目標文件讀入內存然後再寫出來,是嗎? –
如果你必須寫入同一個文件(即更新現有文件),你必須實現('.ToList()'並將整個文件讀到內存中)。如果你寫* *不同*文件,你可以放棄'.ToList()' –
假定你讀你的文件,並得到一個String[]
稱爲file
和數量,要修改,表示爲float
。
比你可以使用下面的代碼首先提取你想要的行。在此之後,你打通float.TryParse(..)
int lineWithParam = 3;
String[] splittedLine = (file[lineWithParam-1]).Split(new char[] { ' ' }, 2);
if(splittedLine.Length == 2)
{
float fact = 0.0f;
String newFact = splittedLine[0];
// or how ever you want to modify your factor
if(float.TryParse(splittedLine[0], out fact))
{
newFact = "" + (fact * 12.3f);
}
file[lineWithParam-1] = newFact + " " + splittedLine[1];
}
這裏可執行例如數量:https://dotnetfiddle.net/NVgETo
在這之後,你可以寫String[] file
回真正的文件。
注:這不會修改file
,如果在給定行的第一個參數是不是一個有效的float
!
你能上傳整個文件的地方?查看完整內容的示例。在http://pastebin.com/例如 – Drarig29
請參閱http://stackoverflow.com/questions/22926306/replace-a-word-from-a-specific-line-in-a-text-file – Mangrio
@ Darig29 http://pastebin.com/raw/Y3YZcaS2 這是一個小例子 –