如何使WPF应用程序不覆盖它创建的文件。 [英] How to make a WPF app not to overwrite the files it creates.

查看:117
本文介绍了如何使WPF应用程序不覆盖它创建的文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序通过按P键创建自己的快照。它在程序所在的目录中创建文件。例如,第一次按P键时,它会创建文件snapshot.png,如果再次按下它,则会创建snapshot_1,第三次创建snapshot_2等等...



但是如果你关闭程序并重新启动它并且这些文件现在存在于目录中,如果现在你按P键它会覆盖它们......



我想要的是检查它要创建的文件是否存在的程序,如果存在,尝试创建一个包含行中下一个数字的文件。如果它也存在,那么尝试下一个,依此类推,直到它找到一个不存在的文件名,然后才创建文件。



你们可以吗?帮我修改代码来做我正在描述的事情吗?



谢谢



什么我试过了:



The program below creates a snapshot of itself by pressing the P key. It creates the file in the directory the program is in. For example the first time you press the P key it creates the file snapshot.png, if you press it again it creates snapshot_1, third time snapshot_2 and so on...

But if you close the program and start it again and those files are existing now in the directory, if now you press P key it overwrites them...

What I want is the program to check if the file that it tring to create exist, and if so, to try to create a file with the next number in the row.. and if that exist too, then try the next, and so on, untill it finds a file name that not exist and only then to create the file.

Can you guys help me modify the code to do what i'm describing?

Thanks

What I have tried:

    string filename = "\\screenshot.png";
    private void Mainwindow_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.P)
        {

            FrameworkElement element = UxVisual as FrameworkElement;

            var pathstr = 

System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

            if (System.IO.File.Exists(pathstr + filename))
            {
                try
                {
                    string i = 
                    filename.Substring(filename.LastIndexOf('_') + 1, 
                    filename.LastIndexOf('.') - (filename.LastIndexOf('_') 
                    + 1));

                    filename = "\\screenshot_" + (Convert.ToInt32(i) +  
                    1).ToString() + ".png";
                }
                catch
                {
                    filename = "\\screenshot_1.png";
                }
            }
            Uri path = new Uri(pathstr + filename);


            CaptureScreen(element, path);
        }

推荐答案

使用Directory.GetFiles Method(System.IO)| Microsoft Docs [ ^ ]获取模式snapshot *中的所有文件,并找到排序结果中的最后一个文件。然后,您可以确定第一个使用哪个号码。
Use Directory.GetFiles Method (System.IO) | Microsoft Docs[^] to get the all the files in the pattern "snapshot*", and find the last one in the sorted result. You can then determine which number to use for the first one.


这篇关于如何使WPF应用程序不覆盖它创建的文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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