通过 VB.NET 创建/编辑文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1332260/
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
Creating/editing textfile through VB.NET
提问by sef
How do I code the algorithm below in VB.NET?
如何在 VB.NET 中编写下面的算法?
Procedure logfile()
{
if "C:\textfile.txt"=exist then
open the textfile;
else
create the textfile;
end if
go to the end of the textfile;
write new line in the textfile;
save;
close;
}
回答by Kirtan
Dim FILE_NAME As String = "C:\textfile.txt"
Dim i As Integer
Dim aryText(4) As String
aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "Another"
aryText(3) = "Little"
aryText(4) = "One"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
For i = 0 To 4
objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
MsgBox("Text Appended to the File")
If you set the second parameter to True
in the System.IO.StreamWriter
's constructor it will append to a file if it already exists, or create a new one if it doesn't.
如果True
在System.IO.StreamWriter
的构造函数中将第二个参数设置为,它将附加到一个文件(如果它已经存在),或者如果它不存在则创建一个新的。
回答by Jakob Gade
This can be achieved in a single line too:
这也可以在一行中实现:
System.IO.File.AppendAllText(filePath, "Hello World" & vbCrLf)
It will create the file if missing, append the text and close it again.
如果丢失,它将创建文件,附加文本并再次关闭它。
See MSDN, File.AppendAllText Method.
请参阅 MSDN,File.AppendAllText 方法。
回答by JP Alioto
It's best to use a component that does this type of logging out of the box. The Logging Application Blockfrom Enterprise Libraryfor example. That way, you get flexibility, scalability and don't have contention with your log file.
最好使用开箱即用进行此类日志记录的组件。例如,来自Enterprise Library的Logging Application Block。这样,您就可以获得灵活性、可扩展性,并且不会与您的日志文件发生争用。
To answer your question specifically (sorry, I don't know VB, but the translation should be simple enough) ...
具体回答你的问题(对不起,我不会VB,但翻译应该足够简单)......
void Main()
{
using( var fs = File.Open( @"c:\textfile.txt", FileMode.Append ) )
{
using( var sw = new StreamWriter( fs ) )
{
sw.WriteLine( "New Line" );
sw.Close();
}
fs.Close();
}
}