2012-05-05 4 views
4

텍스트 파일을 만들고이 파일에 텍스트를 쓰고 싶지만 코드에서 텍스트 파일을 만들 수 없습니다.텍스트 파일 만들기 및 쓰기

오류 메시지 :

UnauthorizedAccessExcepion was unhandled by user code 
Access to the path 'c:\save.txt' is denied. 

내 코드 : Windows에서 C의 루트의 최신 버전에서

Dim fileLoc As String = "c:\save.txt" 
        Dim fs As FileStream = Nothing 
        If (Not File.Exists(fileLoc)) Then 
         fs = File.Create(fileLoc) 
         Using fs 

         End Using 
        End If 
        If File.Exists(fileLoc) Then 
         Using sw As StreamWriter = New StreamWriter(fileLoc) 
          a = "Test: " + TextBox1.Text 
          c = "==============================================" 
          sw.Write(a) 
          sw.Write(c) 
         End Using 
        End If 

답변

3

: 드라이브는 읽기 전용입니다 기본적으로. 다른 폴더에 파일을 넣어보십시오.

조금 강박 받고 직접 C 드라이브 디렉토리를 작성하려는 경우
+0

작동! :] 또한, 어떻게 내 문서 파일에서 txt 파일을 만들 수 있습니까 ?? –

+1

'SaveFileDialog1.InitialDirectory = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); ' – Isuru

+0

Dim fileLoc As String = SaveFileDialog1.InitialDirectory + "\ save.txt"?? –

0

, 당신은이를 사용할 수 있습니다

Imports System.Security.Principal 

Module VistaSecurity 

    'Declare API 
    Private Declare Ansi Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer 
    Private Const BCM_FIRST As Int32 = &H1600 
    Private Const BCM_SETSHIELD As Int32 = (BCM_FIRST + &HC) 

    Public Function IsVistaOrHigher() As Boolean 
     Return Environment.OSVersion.Version.Major < 6 
    End Function 

    ' Checks if the process is elevated 
    Public Function IsAdmin() As Boolean 
     Dim id As WindowsIdentity = WindowsIdentity.GetCurrent() 
     Dim p As WindowsPrincipal = New WindowsPrincipal(id) 
     Return p.IsInRole(WindowsBuiltInRole.Administrator) 
    End Function 

    ' Add a shield icon to a button 
    Public Sub AddShieldToButton(ByRef b As Button) 
     b.FlatStyle = FlatStyle.System 
     SendMessage(b.Handle, BCM_SETSHIELD, 0, &HFFFFFFFF) 
    End Sub 

    ' Restart the current process with administrator credentials 
    Public Sub RestartElevated() 
     Dim startInfo As ProcessStartInfo = New ProcessStartInfo() 
     startInfo.UseShellExecute = True 
     startInfo.WorkingDirectory = Environment.CurrentDirectory 
     startInfo.FileName = Application.ExecutablePath 
     startInfo.Verb = "runas" 
     Try 
      Dim p As Process = Process.Start(startInfo) 
     Catch ex As Exception 
      Return 'If cancelled, do nothing 
     End Try 
     Application.Exit() 
    End Sub 

End Module 
관련 문제