C#中:你将如何通过添加一个号码进行唯一的文件名? [英] C#: How would you make a unique filename by adding a number?

查看:330
本文介绍了C#中:你将如何通过添加一个号码进行唯一的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个它可以是一个文件名作为字符串的FileInfo 的方法,并增加了一个如果该文件存在递增号码的文件名。但不能完全包住我的头围绕如何做到这一点的一个好办法。

例如,如果我有这样的FileInfo

  var文件=新的FileInfo(@C:\\ file.ext);

我想办法给我一个新的FileInfo用的 C:\\文件1.ext 的,如果的 C:\\ file.ext
存在的,而 C:\\文件2.ext 的,如果的 C:\\文件1.ext 的存在等等。事情是这样的:

 公开的FileInfo MakeUnique(FileInfo的的fileInfo)
{
    如果(的fileInfo == NULL)
        抛出新的ArgumentNullException(的fileInfo);
    如果(!fileInfo.Exists)
        返回的fileInfo;    //不知何故从一个我们必须建立新的文件名,测试它,
    //然后再做一次,如果必要的。
}


解决方案

好建议这里很多。我结束了使用由马克在<书面的方法href=\"http://stackoverflow.com/questions/909521/how-to-solve-this-problem-storing-values-persistenly-of-files-in-a-directory/909545#909545\">an回答不同的问题。格式化也一点点,并添加另一种方法,使之更容易一点用从外面。下面是结果:

 私有静态字符串numberPattern =({0});公共静态字符串NextAvailableFilename(字符串路径)
{
    如果已有//短切
    如果(!File.Exists(路径))
        返回路径;    //如果路径有扩展,则只是延长前插入号码模式,并返回下一个文件名
    如果(Path.HasExtension(路径))
        返回GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(路径)),numberPattern));    //否则只是追加模式的路径和返回下一文件名
    返回GetNextFilename(路径+ numberPattern);
}私人静态字符串GetNextFilename(字符串模式)
{
    字符串TMP =的String.Format(模式1);
    如果(TMP ==图案)
        抛出新的ArgumentException(模式必须包含索引占位符,模式);    如果(!File.Exists(TMP))
        返回TMP; //短路,如果没有匹配    INT分= 1,最大值= 2; // min是包容性的,最多是独家/未经测试    而(File.Exists(的String.Format(图案,最大值)))
    {
        MIN = MAX;
        最大* = 2;
    }    而(最大!= MIN + 1)
    {
        INT枢轴=(最大值+最小值)/ 2;
        如果(File.Exists(的String.Format(图案,转轴)))
            分=支点;
        其他
            最大=支点;
    }    返回的String.Format(图案,最大值);
}

只有部分迄今为止测试过它,但如果我找到它的任何错误都会更新。 (马克 US code工作好听!)如果你发现任何问题,请发表评论或编辑或东西:)

I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way.

For example, if I have this FileInfo

var file = new FileInfo(@"C:\file.ext");

I would like the method to give me a new FileInfo with C:\file 1.ext if C:\file.ext existed, and C:\file 2.ext if C:\file 1.ext existed and so on. Something like this:

public FileInfo MakeUnique(FileInfo fileInfo)
{
    if(fileInfo == null)
        throw new ArgumentNullException("fileInfo");
    if(!fileInfo.Exists)
        return fileInfo;

    // Somehow construct new filename from the one we have, test it, 
    // then do it again if necessary.
}

解决方案

Lots of good advice here. I ended up using a method written by Marc in an answer to a different question. Reformatted it a tiny bit and added another method to make it a bit easier to use "from the outside". Here is the result:

private static string numberPattern = " ({0})";

public static string NextAvailableFilename(string path)
{
    // Short-cut if already available
    if (!File.Exists(path))
        return path;

    // If path has extension then insert the number pattern just before the extension and return next filename
    if (Path.HasExtension(path))
        return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));

    // Otherwise just append the pattern to the path and return next filename
    return GetNextFilename(path + numberPattern);
}

private static string GetNextFilename(string pattern)
{
    string tmp = string.Format(pattern, 1);
    if (tmp == pattern)
        throw new ArgumentException("The pattern must include an index place-holder", "pattern");

    if (!File.Exists(tmp))
        return tmp; // short-circuit if no matches

    int min = 1, max = 2; // min is inclusive, max is exclusive/untested

    while (File.Exists(string.Format(pattern, max)))
    {
        min = max;
        max *= 2;
    }

    while (max != min + 1)
    {
        int pivot = (max + min) / 2;
        if (File.Exists(string.Format(pattern, pivot)))
            min = pivot;
        else
            max = pivot;
    }

    return string.Format(pattern, max);
}

Only partially tested it so far, but will update if I find any bugs with it. (Marcs code works nicely!) If you find any problems with it, please comment or edit or something :)

这篇关于C#中:你将如何通过添加一个号码进行唯一的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆