我有一个需要创建日志文件的小型 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
请不要- 我意识到这个功能现在不是特别可操作,我只是想先创建文件,然后我会处理它。