检查文件是否存在,创建新的C# [英] Check if file exist creating new c#

查看:44
本文介绍了检查文件是否存在,创建新的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何确定文件是否存在或正在使用中,以创建一个新的log1,log2,log3等.现在,当我启动应用程序时,因为日志文件正在使用中,所以我无法再启动.我必须创建第二个日志文件或以某种方式写入同一文件吗?

How can I make if file exist or in use in that moment to create new one log1, log2,log3 etc. Now when I start app I can`t start second because log file is in use. I must create second log file or somehow write in same file ?

这是对我有效的解决方案.

here is solution that works fine for me.

if (String.IsNullOrEmpty(this.LogFile1))
            {
                string fn = "\\log.txt";
                while (File.Exists(fn))
                {
                    fn = "\\log1.txt";
                }
                this.LogFile1 = fn;
            }
            return this.LogFile1;

对我的代码进行一些

 if (!File.Exists(this.LogFile))
            {
                log = new StreamWriter(this.LogFile);
            }

            else
            {
                log = File.AppendText(this.LogFile);
            }

现在,如果我有log.txt程序,将创建新的log1.txt.如果它们都存在,将创建log11.txt等.

Now if i have log.txt program will create new log1.txt. If they both exist will create log11.txt and so on.

推荐答案

您可以使用此

          if (String.IsNullOrEmpty(this.LogFile1))
            {
                string fn = "LogFile";
                while (File.Exists(fn))
                {
                    fn = fn + "1";
                }
                this.LogFile1 = fn;
            }
            return this.LogFile1;

这篇关于检查文件是否存在,创建新的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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