[英]Open, Launch or Show a file for the user to read or write in vb.net
这听起来很简单,但我已经搜索过,似乎无法找到一种方法来打开用户刚从我的Windows窗体应用程序创建的日志文件。 文件退出我只想在创建后打开它。
我有一个Dim path As String = TextBox1.Text
,一旦用户在savefiledialog上命名并点击确定我有一个msgbox说“完成”,当你点击OK我试过这个
FileOpen(FreeFile, path, OpenMode.Input)
但没有任何反应。 我只是想让它打开日志并将其显示给用户,以便他们可以再次编辑或保存日志。
这是我得到上述代码的地方。 http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.fileopen.aspx
搜索很困难,因为每个人都试图“打开”文件并在运行时处理它。 我只是试图通过Launching
它来Show
一个文件,就像有人双击它一样。 这是整个导出按钮单击Sub。 它基本上将列表框项目写入文件。
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim sfd As New SaveFileDialog
Dim path As String = TextBox1.Text
Dim arypath() As String = Split(TextBox1.Text, "\")
Dim pathDate As String
Dim foldername As String
foldername = arypath(arypath.Length - 1)
pathDate = Now.ToString("yyyy-MM-dd") & "_" & Now.ToString("hh;mm")
sfd.FileName = "FileScannerResults " & Chr(39) & foldername & Chr(39) & " " & pathDate
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
sfd.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
sfd.ShowDialog()
path = sfd.FileName
Using SW As New IO.StreamWriter(path)
If CkbxFolder.Checked = True Then
SW.WriteLine("Folders")
For Each itm As String In ListBox1.Items
SW.WriteLine(itm)
Next
End If
If CkbxFiles.Checked = True Then
SW.WriteLine("Files")
For Each itm As String In ListBox2.Items
SW.WriteLine(itm)
Next
End If
End Using
MsgBox("Done...")
FileOpen(FreeFile, path, OpenMode.Input) 'Why can't I open a file for you...
End Sub
不要使用旧的VB6方法。 出于兼容性原因,它们仍然在这里,新代码应该使用System.IO命名空间中更强大的方法。
但是,如评论中所述,FileOpen不会为您显示任何内容,只需打开该文件即可
你写道
Using sr = new StreamReader(path)
Dim line = sr.ReadLine()
if !string.IsNullOrEmpty(line) Then
textBoxForLog.AppendText(line)
End If
End Using
或者简单地说(如果文件不是太大)
Dim myLogText = File.ReadAllText(path)
textBoxForLog.Text = myLogText
或者,您可以要求操作系统运行与文件扩展名关联的程序并为您显示该文件
Process.Start(path)
要获得与用户双击它相同的行为,只需使用System.Diagnostics.Process
,并将文件名传递给它的Start
方法:
Process.Start(path)
这将根据文件名的扩展名使用该文件名的默认应用程序打开文件,就像资源管理器双击它时一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.