使用 File.Move 错误时无法创建文件

Cannot Create a file when using File.Move Error

我有一个 .csv 文件作为附加图像,其中包含文件夹和文件列表。我想阅读 .csv 文件并在不同文件夹下重新创建相同的文件夹结构。

例如我有 C:\Data\SourceFolder\Folder2\Folder4\File1.txt ,我想将文件移动到 C:\Data\FilesCopiedfromC\SourceFolder\Folder2\Folder4\File1.txt 。在上面的目标路径中,C:\Data\FilesCopiedfromC 将始终保持不变。我能够在目标中创建文件夹结构,但是当我从源到目标执行 file.move 时,我得到一个 "File cannot be created when it already exists error".

try
        {
            string inputfile = textBox1.Text.ToString();
            using(StreamReader reader = new StreamReader(inputfile))
            {
                string headerline = reader.ReadLine();
                Boolean firstline = true;
                string line = string.Empty;
                 string SourceFileNameCSV;
                string SourceFilePathCSV,totalSourceFilePath, strConstructedDestinationfullpath;
                string[] parts;
                while ((line = reader.ReadLine()) != null)
                {
                    char[] delimiters = new char[] { ',' };
                    parts= line.Split(delimiters);
                    if (parts.Length > 0)
                    {
                        SourceFilePathCSV = parts[0];
                        SourceFileNameCSV = parts[1];
                        totalSourceFilePath = SourceFilePathCSV + "\" + SourceFileNameCSV;
                        strDestinationDynamicPath = SourceFilePathCSV.Replace("C:\Data\", " ").TrimEnd();
                    strConstructedDestinationfullpath = Path.Combine(strDestinationStaticPath, strDestinationDynamicPath);
                        if (!string.IsNullOrEmpty(strConstructedDestinationfullpath))
                        {
                            if (!Directory.Exists(strDestinationDynamicPath))
                            {
                                Directory.CreateDirectory(strConstructedDestinationfullpath);
                            }
                            // File.Move(totalSourceFilePath, strConstructedDestinationfullpath);
                        }
                    }

                }
            }

        }//try

感谢任何帮助。

您需要为目的地指定一个文件名,目前您只提供一个路径:

File.Move(
    totalSourceFilePath, 
    Path.Combine(strConstructedDestinationfullpath, Path.GetFileName(totalSourceFilePath));

这是因为,显然,该文件已经存在于目标中。您可以做的是检查文件是否存在,如果存在则删除:

if (System.IO.File.Exists("filename"))

{

//delete

   System.IO.File.Delete("filename"); //try/catch exception handling 
  needs to be implemented

}