繁体   English   中英

通过递归方法重试3次如果文件在c#中存在

[英]Retry for three times If the File Exists in c# through Recursive Method

任何人都可以通过递归方法提供解决方案来帮助我

我的要求是我想要一个递归方法,需要运行以下代码三遍:

下面是我的 C# 工作代码:

public void Process()
 {
     bool exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");

     for(int i = 0; i < 3 && exists; i++)
     {    
         System.Diagnostics.Process.Start("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\SvnUninstallation.exe");
         Sleep(2000); // or long enough to ensure the uninstall process finishes executing
         exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");             
     }
     Console.WriteLine(exists);
     Console.ReadLine();

 }

带有 for 循环的原始代码完全符合递归函数的功能。 我对发布此代码不太满意。 我能想到使用递归函数的唯一有效时间是在构建某种树结构时。

您还应该注意,如果您没有正确实现递归函数,并且没有中断您可能使用递归函数创建的连续循环,您将遇到StackOverflow异常,因为被调用的方法被添加到堆栈中,并且堆栈最终会耗尽内存。

这是根据您的需要实现递归函数的一种方法:

public void Process(int count = 0)
    {
        bool exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");

        if (exists && count < 3)
        {
            System.Diagnostics.Process.Start("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\SvnUninstallation.exe");
            Thread.Sleep(2000); // or long enough to ensure the uninstall process finishes executing

            //File exists
            Console.WriteLine("File exists");

            Process(++count);
        }
        else
        {
            Console.WriteLine("Exceeded retry of 3 times. File did not uninstall.");
        }

        if (!exists)
            Console.WriteLine("File uninstalled");

    }

这是递归方法的代码片段。 尝试一下,如果您有任何疑问,请告诉我。

static bool FileExists(bool _fileexists, int Count)
    {
        //Console.WriteLine("Inside File Check");
        Count++;
        System.Diagnostics.Process.Start("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\SvnUninstallation.exe");
        Thread.Sleep(2000);
        return (_fileexists == false && Count <=3) ? FileExists(File.Exists("C:\\IFRToolLog1.txt"),Count) : true;            
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM