我有一个需要创建日志文件的小型VB应用程序,理想情况下我喜欢用户桌面,因为它很容易看到。
但是,当我尝试创建文件(* .txt文件)时,出现以下错误 -
mscorlib.dll中出现'System.UnauthorizedAccessException'类型的第一次机会异常
现在,很明显这是一个权限问题,但我不知道如何解决它,所以我想知道是否有人可以帮助我?感谢。
创建文件的完整代码(取自MSDN,并稍微修改) -
Imports System
Imports System.IO
Imports System.Text
Module write_text
Public Class Log_File
'*'
' Createa a log file on the users desktop and adds the 'output' text to it
'
' @param required string output The text to output to the log
'*'
Public Shared Sub write_to_file(ByVal output As String)
Dim path As String ' The path to where the file to create and write should be saved
Dim file_name As String ' The name of the log file that is to be created
Debug.Print(vbCrLf & " write_to_file(){" & vbCrLf)
' Set the error handler
On Error GoTo ExitError
path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
file_name = "MusicRenaming - " & Date.Today & ".txt"
Debug.Print(" Log file: " & path & "\" & file_name)
' Check if the file exists
If File.Exists(path) = False Then
' Create a file to write too.
Dim sw As StreamWriter = File.CreateText(path)
sw.WriteLine("Hello")
sw.WriteLine("And")
sw.WriteLine("Welcome")
sw.Flush()
sw.Close()
Debug.Print(" File had to be created")
End If
' Open the file to write too
Dim sr As StreamReader = File.OpenText(path)
Do While sr.Peek() >= 0
Console.WriteLine(sr.ReadLine())
Debug.Print(" Output to file complete")
Loop
' Close the file
sr.Close()
Debug.Print(vbCrLf & " }")
ExitError:
If Err.Number <> 0 Then functions.error_handler()
End Sub
End Class
End Module
请不要 - 我意识到该功能现在不是特别可操作,我只是想先创建文件,然后我会继续处理。
答案 0 :(得分:0)
感谢@RubensFarias发布in this thread的答案,我能够解决这个问题。
我还在@minitech的建议中将try...catch
方法纳入了我的原始问题的评论中,所以希望他对我解决他的问题感到满意:)
Imports System.IO
Module write_text
Public Class Log_File
'*'
' Createa a log file on the users desktop and adds the 'output' text to it
'
' @param required string output The text to output to the log
'*'
Public Shared Sub write_to_file(ByVal output As String)
Dim file_name As String ' The name of the log file that is to be created
Dim file_path As String ' The full path to where the file to create and write should be saved
Dim file_exists As Boolean ' Whether or not the file already exists
Try
file_name = "MusicRenaming - " & DateTime.Today.ToString("dd-mm-yyyy") & ".txt"
file_path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\" & file_name
file_exists = File.Exists(file_path)
Using sw As New StreamWriter(File.Open(file_path, FileMode.OpenOrCreate))
sw.WriteLine(output)
End Using
Catch oError As Exception
functions.error_handler(oError)
End Try
End Sub
End Class
End Module