在 C# 中将 txt 文件截断 'x' 字节

Truncating a txt file by 'x' bytes in C#

我想在阅读内容后删除文本文件的最后一行。文本文件非常大,因此由于性能问题 Reading/Writing 不是一个选项。

我目前的想法是计算最后一行代表的字节数(连同进位return)并截断文件。

我看到的很多选项都提到了使用 "Filestream.setLength()",我对它的工作原理感到困惑。

这不会只是写回文件,而是在特定字节数处停止文件,因为 'read' 函数读取字节并将它们写回缓冲区?或者我可以在阅读时使用此功能,并将文本文件的 "end position" 移回 24 个字节吗?

这是我当前使用的代码

try
            { 
            //reading
            using (StreamReader reader = new StreamReader(filePath))
            {
                    while (!reader.EndOfStream)
                    {
                        //gets the line
                        line = reader.ReadLine();
                        if (!line.StartsWith("KeyWord", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //add number of lines
                            lineCount += 1;
                        }
                        else
                        {
                            //Finds the occurence of the first numbers in a string
                            string resultString = Regex.Match(line, @"\d+").Value;
                            long lastLineBytes = 0;
                            foreach (char c in line)
                            {
                                //each char takes up 1 byte
                                lastLineBytes++;         
                            }
                            //carriage return
                            lastLineBytes += 2;
                            long fileLength = new FileInfo(filePath).Length;
                            Trace.WriteLine("The length of the file is " + fileLength);

                            //the size of the file - the last line
                            //truncate at this byte position, and we will be done. 
                            long newFileLength = fileLength - lastLineBytes;
                            //Truncation goes ehre
                        }
                }
          }
        }
        catch (Exception e)
        {
            throw e;
        }

如果您更改流的大小,它将仅重写文件 table 索引以指向左侧字节。

对于你的第二个问题,是的,你可以使用它来读取内容(在这个例子中我假设ASCII编码,使用合适的编码器)。

FileStream str = //get the stream
byte[] data = new byte[str.Length];
str.Read(data, 0, data.Length);
string theContent = System.Text.Encoding.ASCII.GetString(data);