2009-04-15 19 views

回答

3

有很多原因,一個文件可能不寫,例如:

  • 它寫保護
  • 這是一個只讀介質(例如CD-ROM)
  • 用於運行代碼的用戶帳戶不具有對文件的寫入訪問權
  • 該文件位於不允許書寫的文件共享上

你可以檢查其中的一些,但唯一可以肯定測試的方法是實際嘗試打開文件進行寫入。

您可以使用GetAttrSetAttr函數來查找和更改只讀標誌。

文件無法寫入的一些原因根本無法修復(如CD-ROM上的文件),或無法從程序修復。如果用戶帳戶不具有寫權限的文件,這是不可能的,它有權更改權限...

+0

在我們的情況下文件有時不可寫入,因爲它們通過我們無法控制的進程複製。所以我們只想涵蓋所有情況。 – Laurent 2009-04-15 08:14:28

-1
'Getting and Setting File Attributes 

Declare Function SetFileAttributes Lib "kernel32" _ 
Alias "SetFileAttributesA" (ByVal lpFileName As _ 
String, ByVal dwFileAttributes As Long) As Long 
Declare Function GetFileAttributes Lib "kernel32" _ 
Alias "GetFileAttributesA" (ByVal lpFileName As _ 
String) As Long 

Public Function GetAttributes(Filename As String, _ 
Archive As Boolean, Hidden As Boolean, _ 
ReadOnly As Boolean, System As Boolean) 

    'Dimension and setup some variables. 
    Dim Data As Long 
    Archive = False: Hidden = False: ReadOnly = False 

    'Get Data and check for success. 
    Data = GetFileAttributes(Filename) 
    If Data = 0 Then GetAttributes = 0 Else GetAttributes = 1 

    'Work out what it is. 
    If Data = 128 Then Exit Function 
    If Data - 32 >= 0 Then Archive = True: Data = Data - 32 
    If Data - 4 >= 0 Then System = True: Data = Data - 4 
    If Data - 2 >= 0 Then Hidden = True: Data = Data - 2 
    If Data - 1 >= 0 Then ReadOnly = True: Data = Data - 1 

End Function 

Public Function SetAttributes(Filename As String, _ 
Archive As Boolean, Hidden As Boolean, _ 
ReadOnly As Boolean, System As Boolean) 

    'Dimension a Variable. 
    Dim Data As Long 

    'Work out what Data should be. 
    Data = 0 
    If Archive = True Then Data = Data + 32 
    If Hidden = True Then Data = Data + 2 
    If ReadOnly = True Then Data = Data + 1 
    If System = True Then Data = Data + 4 
    If Data = 0 Then Data = 128 

    'Set the attributes and check for success. 
    SetAttributes = SetFileAttributes(Filename, Data) 

End Function 
2

使用GETATTR和SETATTR

Dim attributes As VbFileAttribute 

attributes = GetAttr("C:\foo.txt") 
If (attributes And vbReadOnly) Then 
    attributes = attributes - vbReadOnly 
    SetAttr "C:\foo.txt", attributes 
End If 

使用FileSystemObject(需要項目引用到Microsoft腳本運行時)

Dim fso As New FileSystemObject 
Dim fil As File 

Set fil = fso.GetFile("C:\foo.txt") 
If (fil.attributes And ReadOnly) Then 
    fil.attributes = fil.attributes - ReadOnly 
End If 
相關問題