【问题标题】:How to create a copy of a file within a folder and get the name of the automatic copy C#?如何在文件夹中创建文件副本并获取自动副本 C# 的名称?
【发布时间】:2016-06-15 23:24:08
【问题描述】:

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

工作流程如下:

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)

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

【问题讨论】:

  • File.Exists()如何表示文件已打开?
  • 做一些研究,伙计。如果您只需花 2 分钟时间看一下,就会有很多答案。 stackoverflow.com/questions/876473/… 和 stackoverflow.com/questions/13049732/…
  • 这段代码实际上是用什么语言编写的?
  • 您可能想要复制 (1) 之后的扩展名吧?
  • 你是绝对正确的@RickS,我很着急,根本没有找到那个参考。 13049732 有答案。

标签: c#


【解决方案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++;
    }
}

【讨论】:

    【解决方案2】:

    这也将作为扩展名的后缀:

    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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      相关资源
      最近更新 更多