Vb6 如何使文件在VB中可写?
我正在寻找最简单的方法来测试一个文件是否可写,以及它是否是只读的,以更改其访问权限使其可写Vb6 如何使文件在VB中可写?,vb6,permissions,Vb6,Permissions,我正在寻找最简单的方法来测试一个文件是否可写,以及它是否是只读的,以更改其访问权限使其可写 欢迎向正确方向提出任何建议或指点 文件不可写的原因有很多,例如: 'Getting and Setting File Attributes Declare Function SetFileAttributes Lib "kernel32" _ Alias "SetFileAttributesA" (ByVal lpFileName As _ String, ByVal dwFileAttribute
欢迎向正确方向提出任何建议或指点 文件不可写的原因有很多,例如:
'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
- 它是写保护的
- 它位于只读介质(如CD-ROM)上
- 用于运行代码的用户帐户没有对文件的写入权限
- 该文件位于不允许写入的文件共享上
文件不可写的某些原因根本无法修复(如CD-ROM上的文件),或者无法从程序中修复。如果用户帐户没有对文件的写入权限,则不太可能有权使用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