【问题标题】:Better Way to Copy Move Rename File, Visual Basic (VS 2012 V11)复制移动重命名文件的更好方法,Visual Basic (VS 2012 V11)
【发布时间】:2013-05-02 03:31:57
【问题描述】:

我想复制、重命名文件并将其移动到新位置。根据http://msdn.microsoft.com/en-us/library/36xbexyf(v=vs.90).aspx,下面的代码应该这样做:

此示例将文件 Test.txt 复制到目录 TestFiles2 和 将其重命名为 NewFile.txt。

My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2", "NewFile.txt", FileIO.UICancelOption.DoNothing)

但是,当我键入此代码时,它只会将“NewFile.txt”参数视为处理覆盖的布尔参数。我认为这是网站部分的错误。

如果我不能使用“My.Computer.FileSystem.CopyFile”(除非我做错了什么)来复制重命名和移动文件,那么有没有更好的方法:

' Rename the file to be copied the name you want it to be in the new location
My.Computer.FileSystem.RenameFile("C:\OriginalFile.txt", "OriginalFileTemporaryName.txt")

' Copy the file to the new location and overwrite if it exists there
My.Computer.FileSystem.CopyFile ("C:\OriginalFileTemporaryName.txt", "C:\UserFiles\TestFiles2", True)

' Rename the original file back to it's original name
My.Computer.FileSystem.RenameFile("C:\OriginalFileTemporaryName.txt", "OriginalFile.txt")

上面的问题是我可能最终将原始文件重命名为原始文件位置中已经存在的临时名称。我想避免这种情况。我也不想重命名目标文件夹中的复制文件,因为我没有看到强制覆盖“My.Computer.FileSystem.RenameFile”的选项

这甚至是一个半体面的解决方案吗? 没有更好的方法吗?

【问题讨论】:

    标签: vb.net copy rename overwrite file-copying


    【解决方案1】:

    我认为你有语法错误。您试图将目标文件名作为两个参数提供 - 目录名和文件名,而您应该将两者都作为一个字符串提供。

     My.Computer.FileSystem.CopyFile ("C:\UserFiles\TestFiles\test.txt", "C:\UserFiles\TestFiles2\NewFile.txt")
    

    这样。第三个参数可以是布尔值 (True/False) - 如果目标文件存在,您是否要覆盖它。

    如果你想先检查文件是否存在,看看 System.IO.File 类,它有“Exists”方法,它接受文件名并返回布尔值。它还具有操作文件的方法,您可以使用这些方法代替 FileSystem 类,尽管没有性能优势。

    【讨论】:

      【解决方案2】:

      这在网站上看起来确实像是一个错误。不过,这不应该阻止我们;只需将目录和文件名放入同一个参数即可:

      My.Computer.FileSystem.CopyFile("C:\UserFiles\TestFiles\test.txt", "C:\UserFiles\TestFiles2\NewFile.txt", FileIO.UICancelOption.DoNothing)
      

      (如果要强制覆盖,把第三个参数改成True。我不知道你可以覆盖并在同一个调用中传递CancelOption.DoNothing。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 2013-07-15
        • 2012-01-29
        • 2021-02-21
        相关资源
        最近更新 更多