[英]C# How to delete last 2 characters from text file and write into the same line at the end my text?
var lines2 = File.ReadAllLines("file.path");
File.WriteAllLines("file.path", lines2.Take(lines2.Length - 2).ToArray());
using (StreamWriter db = new FileInfo("file.path").AppendText())
db.Writeline("");
這是我的代碼,刪除最后兩行,然后將我的文本寫到新行中,效果很好,
但是,我需要將最后2個字符刪除到最后一行(文本文件只有一行),並添加到同一行而沒有空格或換行,這是我的文本。
我嘗試了幾次,但是失敗了。 谷歌也不能幫助我。
例:
之前的文字:您好,這是一個例子!
刪除最后兩個字符:您好,這是一個示例
添加到文本:???
之后的文字:您好,這是一個例子???
我想刪除最后兩個字符! 並在最后一個字后面加上我想要的任何內容
如果您想要做的只是將所有內容都切掉然后追加,則無需閱讀所有內容。 就像是:
using(var fs = new FileStream("file.path"))
{
fs.Seek(-2,SeekOrigin.End);
var newText = Encoding.UTF8.GetBytes("new content");
fs.Write(newText,0,newText.Length);
fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
}
(如果你不快樂不必自己做編碼步驟,你可以移動SetLength()
調用后,立即Seek
,然后包裹FileStream
以適當StreamReader
並從那里開始使用它)
刪除最后一行的最后2個字符
您可以使用此:
string[] allLines = File.ReadAllLines("file.path");
if(allLines.Length > 0)
{
string lastLine = allLines.Last();
if(lastLine.Length >= 2)
{
lastLine = lastLine.Remove(lastLine.Length - 2);
}
allLines[allLines.Length - 1] = lastLine;
}
File.WriteAllLines("file.path", allLines);
// Get file content
string fileContent = File.ReadAllText("file.path");
// Remove the last to characters
fileContent = fileContent.Remove(fileContent.Length - 2) + "your text...";
// Write content back to the file
File.WriteAllText("file.path", fileContent);
我將如何做(我跳過一些我認為您知道的步驟)
首先,獲取文件內容
第二:
string MyFileContext = MyFileContext.Substring(0, MyFileContext.Length - 2);
MyFileContext += "What you want";
三:保存:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.