如何在文件夹中创建文件的副本并获取自动副本C#的名称?

时间:2016-06-15 15:06:46

标签: c#

在应用程序中,用户可以打开已保存的文件。 我的目标是检查文件是否已经打开,并且只有在创建本地副本时才允许用户再次打开它,以便不能同时修改同一文件。

工作流程如下:

if (File.Exists(strFileName))
   bCreateCopy = AlertBox.Display("File already open. Work on a copy?", true/false);

if (bCreateCopy == true)
{
    strNewAutomaticFileName = createAutomaticFileName (sourceFile)
    File.Copy(sourceFile, strNewAutomaticFileName );
}

是否有一种方法可以在'createAutomaticFileName()'中完成我需要的工作?

我正在考虑创建典型的大炮名称:

 sourceFile - copy
 sourceFile - copy (1)
 sourceFile - copy (2)

是否有更好的解决方法来实现此目的?

2 个答案:

答案 0 :(得分:1)

如果我理解你,那就尝试一下:

public string createAutomaticFileName(string sourceFile)
{
   var done = true;
   int i = 0;       
   while (done)
   {
        var newFileName = (i == 0) ? string.Format("{0} - copy ", sourceFile) : string.Format("{0} - copy ({1})", sourceFile, i.ToString());
        if (!File.Exists(newFileName)) 
        {
            return newFileName;
        }
        i++;
    }
}

答案 1 :(得分:0)

这也是扩展名的后缀:

if (File.Exists(strFileName))
{
   bCreateCopy = AlertBox.Display("File already open. Work on a copy?", true/false);
}

if (bCreateCopy == true)
{
    strNewAutomaticFileName = createAutomaticFileName(sourceFile)
    File.Copy(sourceFile, strNewAutomaticFileName );
}

...

private string createAutomaticFileName(string filePath, int count = 1)
{
    var pathWithoutExtension = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
    var newFilePath = String.Format("{0} - copy ({1}){2}", pathWithoutExtension, count, Path.GetExtension(filePath));

    if (File.Exists(newFilePath))
    {
        return createAutomaticFileName(filePath, ++count);
    }

    return newFilePath;
}

当然,在您已经知道初始文件存在之后,您需要使用它,就像在您的示例中一样。

相关问题