vb.net 清除文本文件而不删除它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27622194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clearing a text file without deleting it
提问by Coding Duchess
I have a text file to which I will be appending data(hence I can't just overwrite the file). The thing is that originally it does contain content I do not want, so before I start appending new data. Is there a way to clear the file without having to delete and then re-create it?
我有一个文本文件,我将向其中附加数据(因此我不能只覆盖该文件)。问题是它最初确实包含我不想要的内容,所以在我开始附加新数据之前。有没有办法清除文件而不必删除然后重新创建它?
回答by rory.ap
You can start by overwriting the file with an empty string, and then append your data afterwards. You could use this to overwrite the file:
您可以先用空字符串覆盖文件,然后再追加数据。您可以使用它来覆盖文件:
System.IO.File.WriteAllText(Path, "")
The benefit of this as opposed to deleting and recreating the file is that you will preserve the original create date of the file along with any other metadata.
与删除和重新创建文件相比,这样做的好处是您将保留文件的原始创建日期以及任何其他元数据。
回答by Neolisk
Yes, most .NET methods allow you to either append or overwrite. You already found one method that could do it - File.WriteAllText. The only drawback is that it's non-streamed, so for a lot of content, you may need a lot of memory. File.Createis a stream version. It may look like more code (and it is), but it can be useful in situations when you simply cannot afford to put all your contents in memory at once. Example from MSDN:
是的,大多数 .NET 方法都允许您追加或覆盖。您已经找到了一种可以做到的方法 - File.WriteAllText。唯一的缺点是它是非流式传输的,因此对于大量内容,您可能需要大量内存。File.Create是一个流版本。它可能看起来像更多的代码(确实如此),但在您根本无法一次性将所有内容放入内存的情况下,它可能很有用。来自 MSDN 的示例:
Dim path As String = "c:\temp\MyTest.txt"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(
"This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
回答by jcwrequests
http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength(v=vs.110).aspx
FileStream.SetLength(0);
FileStream.SetLength(0);
Set the FileStream Length to zero. I have included the docs from MSDN.
将 FileStream 长度设置为零。我已经包含了来自 MSDN 的文档。