2013-03-02 3 views
0

У меня есть небольшое приложение VB, которое должно создать файл журнала, и в идеале мне бы это понравилось на рабочем столе пользователей, так как это легко увидеть.Разрешение отклонено при попытке создать файл на рабочем столе пользователей

Однако, когда я пытаюсь создать файл (* .txt файл), я получаю следующее сообщение об ошибке -

Первый шанс исключение типа «System.UnauthorizedAccessException» произошло в mscorlib.dll

Теперь кажется довольно очевидным, что это проблема с разрешениями, но я не знаю, как обойти его, поэтому мне интересно, может ли кто-нибудь помочь мне? Благодарю.

Полный код для создания файла (из MSDN и modifided очень немного) -

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

Пожалуйста, не используйте 'On Error '. Это не VB6. :( – Ryan

+0

Любые подсказки о том, что я использую для захвата ошибок? Я больше привык к VBA, где это обычная практика. –

+0

Блок «Попробуйте ... Catch» и сделайте его более конкретным. И используйте блоки 'Using', чтобы что ваши потоки будут утилизированы должным образом. Или «File.ReadLines», это тоже работает. Но полностью избавитесь от обработки ошибок и узнайте, где происходит ошибка, точно. Затем убедитесь, что путь правильный. – Ryan

ответ

0

Спасибо за ответ от @RubensFarias in this thread Я смог исправить эту проблему.

Я также включил метод try...catch как предложено @minitech в комментариях к моему Origianl вопроса, так что надеюсь, что он удовлетворен тем, что я обратился к его заботе :)

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 
+3

Вы можете заметить что-то странное с 'DateTime.Today.ToString (« dd-mm-yyyy »)' - это потому, что «мм» означает минуты. Вероятно, MM ", что означает месяцы. –

+0

Спасибо, я этого не заметил, но это действительно выводило только« 00 ». –

Смежные вопросы