【问题标题】:Incrementing file name goes on infinite loop logic error C#递增文件名出现无限循环逻辑错误 C#
【发布时间】:2016-09-17 15:14:13
【问题描述】:

我正在尝试上传一个文件,然后复制该文件并将其移动到另一个名为“Converted”的文件夹中。如果文件已存在于 Converted 文件夹中,则文件名应递增。我的代码是一个无限循环,直到我停止我的程序才会停止。

例如反射纸.docx

代码:

string myFile = fileDoc.Text; //C:\Users\Admin\Documents\ThesisSampleFolders\Original\Reflection Paper.docx
string targetPath2 = @"C:\Users\Admin\Documents\ThesisSampleFolders\Converted";
string result = Path.GetFileName(myFile);

string combinePath = System.IO.Path.Combine(targetPath2, result);

int count = 1;

string fileNameOnly = Path.GetFileNameWithoutExtension(combinePath);
string extension = Path.GetExtension(combinePath);
string path = Path.GetDirectoryName(combinePath);
string newFullPath = combinePath;
string tempFileName = "";

while (File.Exists(newFullPath))
{
     tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
     newFullPath = Path.Combine(path, tempFileName + extension);
     File.Copy(myFile, newFullPath);
     //break;
}

问题是,我尝试输入break,但发生的情况是,在它第一次递增后,出现错误提示 Reflection Paper(1).docx 应该成为 Reflection Paper(2) 时已经存在).docx。我为此道歉。我真的希望你能帮助我。非常感谢您的帮助!

【问题讨论】:

    标签: c# file infinite-loop


    【解决方案1】:

    这应该可行:

    do
    {
        if (File.Exists(newFullPath)) // if file exists get a new file name
        {
            tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
            newFullPath = Path.Combine(path, tempFileName + extension);
        }
        else // copy with the new path
        {
    
            File.Copy(myFile, newFullPath);
    
            break;
        }
    }
    while (true);
    

    更改为 do { } while 并带有中断条件。

    【讨论】:

    • 它就像我想要的那样工作。非常感谢!!!!!这是一个很大的帮助!
    【解决方案2】:

    你有一个缺陷是没有打破你的 while 循环。

    1. 你检查一个文件是否存在
    2. 创建一个临时名称
    3. 使用临时名称复制文件
    4. 检查文件是否存在(是的,因为您在第 3 步中复制了它!)
    5. 创建临时名称..等

    固定代码

    bool copied = false;
    while (!copied)
    {
         if(File.Exists(newFullPath)){
            tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
            newFullPath = Path.Combine(path, tempFileName + extension);
            continue;
         }
         File.Copy(myFile, newFullPath);
         copied = true;
         //break;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      相关资源
      最近更新 更多