2011-02-01 83 views
1

如何在vb6中使用cmd命令重命名文件?如何使用vb6中的cmd命令重命名文件?

我的代码有什么问题?

Shell "cmd ren D:\before.txt after.txt" 
+1

你得到什么错误? – 2011-02-01 03:32:02

+0

没有错误。但它只显示我的cmd窗口,它不重命名文件。为什么? – faressoft 2011-02-01 04:04:53

回答

-2

为什么使用命令行而不是代码重命名文件?除非你有充分的理由使用cmd,否则我会推荐使用Windows API,更可靠。这是一个使用SHFileOperation重命名文件的示例。把它放到任何模块或类中。

Option Explicit 

Private Type SHFILEOPSTRUCT 
     hwnd As Long 
     wFunc As Long 
     pFrom As String 
     pTo As String 
     fFlags As Integer 
     fAnyOperationsAborted As Long 
     hNameMappings As Long 
     lpszProgressTitle As Long ' only used with FOF_SIMPLEPROGRESS; sets dialog title 
End Type 

' For info, see: http://msdn.microsoft.com/en-us/library/bb759795%28v=vs.85%29.aspx 
Private Const FO_COPY     As Long = &H2 
Private Const FO_DELETE     As Long = &H3 
Private Const FO_MOVE     As Long = &H1 
Private Const FO_RENAME     As Long = &H4 
Private Const FOF_ALLOWUNDO    As Long = &H40 
Private Const FOF_CONFIRMMOUSE   As Long = &H2 
Private Const FOF_FILESONLY    As Long = &H80 
Private Const FOF_MULTIDESTFILES  As Long = &H1 
Private Const FOF_NO_CONNECTED_ELEMENTS As Long = &H2000 
Private Const FOF_NOCONFIRMATION  As Long = &H10 
Private Const FOF_NOCONFIRMMKDIR  As Long = &H200 
Private Const FOF_NOCOPYSECURITYATTRIBS As Long = &H800 
Private Const FOF_NOERRORUI    As Long = &H400 
Private Const FOF_NORECURSION   As Long = &H1000 
Private Const FOF_RENAMEONCOLLISION  As Long = &H8 
Private Const FOF_SILENT    As Long = &H4 
Private Const FOF_SIMPLEPROGRESS  As Long = &H100 
Private Const FOF_WANTMAPPINGHANDLE  As Long = &H20 
Private Const FOF_WANTNUKEWARNING  As Long = &H4000 

Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long 

Public Function FileRename(OldFileNameAndPath As String, NewFileNameAndPath As String) As Boolean 
    Dim oP As SHFILEOPSTRUCT, lRet As Long 
    On Error GoTo Err 

    ' Prepare FILEOP struct 
    With oP 
     .wFunc = FO_RENAME       ' Set function 
     .pTo = NewFileNameAndPath     ' Set new path 
     .pFrom = OldFileNameAndPath     ' Set current path 
     .fFlags = FOF_SILENT + FOF_SIMPLEPROGRESS ' Set your flags; FOF_SILENT + FOF_SIMPLEPROGRESS will silently rename a file 
    End With 

    ' Perform operation 
    lRet = SHFileOperation(oP) 

    If lRet = 0 Then 
     FileRename = True 
    Else 
     FileRename = False 
    End If 

    Exit Function 
Err: 
    ' TODO: Log Error 
End Function 
7

您需要一个/ C或/ K才能真正正常工作。见Cmd /?了解更多信息。

Shell函数也与命令行提示符不同。它是VB和Windows旧版本的补充,并且是WinExec()API的封装。

要重命名VB6一个文件,使用名称声明:

Name "D:\before.txt" As "after.txt"