vb.net 如何检查文本文件是否打开并关闭文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6706312/
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
How to check if the text file is open and close the text file?
提问by Dan
I am trying to save the text file in this path:"C:\Test\test.txt" and when the file is already opened I need to check whether the file is opened and I need to close it before writing it to the file.
我正在尝试将文本文件保存在此路径中:“C:\Test\test.txt”,当文件已打开时,我需要检查文件是否已打开,并且需要在将其写入文件之前将其关闭.
Here is the code for saving the file: Dim myfile As String = "C:\Test\test.txt"
这是保存文件的代码: Dim myfile As String = "C:\Test\test.txt"
'Check if file exists
If System.IO.File.Exists(myfile) = True Then
'Delete it!
Dim fi As New FileInfo(myfile)
fi.Delete()
End If
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
IO.Directory.CreateDirectory("C:\Test")
Dim w As New IO.StreamWriter("C:\Test\test.txt")
Dim i As Integer
For i = 0 To CheckedListBox1.Items.Count - 1
w.WriteLine(CheckedListBox1.Items.Item(i))
Next
w.Close()
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
End Using
If I am doing this way I am able to close the notepad process but I need to close the specific opened text file:
如果我这样做,我可以关闭记事本进程,但我需要关闭特定打开的文本文件:
Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")
Process() = CType(Interaction.GetObject("C:\Test\test.txt"), Diagnostics.Process())
For Each p As Process In Process
p.Kill()
Next
回答by sealz
I do not believe there is a property that will allow for you to check if the streamreader is open or not.
我不相信有一种属性可以让您检查流阅读器是否打开。
Best practice seems to be to .close
the reader when done with it. (All in the method that it was used in.)
最佳实践似乎是.close
读者完成后。(都在使用它的方法中。)
You could try a try block
to handle the exception if you are still getting one.
try block
如果您仍然遇到异常,您可以尝试处理异常。
May be able to find additional info and some sample code here. Good Luck.
可以在此处找到其他信息和一些示例代码。祝你好运。
EDIT: You may be able to check using this. IO.File
编辑:您可以使用它进行检查。 IO.File
Private Function CheckFile(ByVal filename As String) As Boolean
Try
System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
FileClose(1)
Return False
Catch ex As Exception
Return True
End Try
End Function
回答by sealz
What about :
关于什么 :
If File.Exists("File1.txt") = False Then
File.CreateText("File1.txt").Close()
Else
Exit Sub
End If
If File.Exists("File2.txt") = False Then
File.CreateText("File2.txt").Close()
Else
Exit Sub
End If
End If
回答by Jeremy Thompson
Private Sub IsFileOpen(ByVal file As FileInfo)
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
Catch ex As IOException
If IsFileLocked(ex) Then
'do something here, either wait a few seconds, close the file if you have
'a handle, make a copy of it, read it as shared (FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.ReadWrite).
'I dont recommend terminating the process - which could cause corruption and lose data
End If
Catch ex As Exception
End Try
End Sub
Private Shared Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
回答by Dan
The following function can be used to determine is a file is already open (True) or not (False). Action can then be based on the Function result.
以下函数可用于确定文件是否已打开 (True) 或未打开 (False)。然后可以基于函数结果采取行动。
Public Function IsFileOpen(ByVal xFileName As String, ByVal xFileChannel As Integer) As Boolean
' ************************************************************
' * Function: IsFileOpen
' * Purpose: To determine if a file is already open.
' * Can be used to determine if a file should be closed.
' * Syntax:
' * Dim bResult as Boolean
' *
' * bResult = IsFileOpen("C:\Test.txt", 1)
' *
' * OR
' *
' * If IsFileOpen("C:\Test.txt", 1) = True Then
' * Microsoft.VisualBasic.FileClose(1)
' * End If
' *
' ************************************************************
Try
Microsoft.VisualBasic.FileOpen(xFileChannel, xFileName, OpenMode.Input, OpenAccess.Read, OpenShare.Default)
Catch
' File Already Open Error Number = 55
If Trim(Err.Number.ToString) = "55" Then
Return True
Else
Return False
End If
End Try
End Function
回答by Jon Boy
I was having this problem with a .csv file my program attaches to an email. I added code to clear the Attachments collection in the MailMessage object then disposing the MailMessage and Attachment objects after the mail is sent. That appears to have fixed the problem.
我的程序附加到电子邮件的 .csv 文件遇到了这个问题。我添加了代码来清除 MailMessage 对象中的 Attachments 集合,然后在发送邮件后处理 MailMessage 和 Attachment 对象。这似乎解决了问题。