本文介绍了C# - 追加数到文件存在保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个截屏程序和所有工作很大。唯一的问题是,我不知道我怎么可以让这样的截图将保存有附加的数字。

I have created a screenshot program and all is working great. The only problem is, I am not sure how I can make it so the screenshots are saved with appending numbers.

例如:截图1,截图2,截图3截图4等

Example: Screenshot 1, Screenshot 2, Screenshot 3, Screenshot 4, etc.

显然,这可以应用到其他文件被保存。有任何想法吗?谢谢你。

Obviously this could be applied to other files being saved. Any ideas? Thank you.

推荐答案

下面是我经常使用这种非常情况下的方法。只是通过像截图的字符串,它会发现在截图[数字]的形式最低的可用文件名(或只是截图如果没有任何的话):

Here is a method I use frequently for this very case. Just pass in a string like "Screenshot" and it will find the lowest available filename in the format of "Screenshot [number]" (or just "Screenshot" if there aren't any already):

private string GetUniqueName(string name, string folderPath)
{
    string validatedName = name;
    int tries = 1;
    while (File.Exists(folderPath + validatedName))
    {
        validatedName = string.Format("{0} [{1}]", name, tries++);
    }
    return validatedName;
}

(注:这是一个稍微简化版本,不带文件扩展名在内)。

(Note: this is a slightly simplified version that doesn't take file extensions into account).

这篇关于C# - 追加数到文件存在保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 00:18