首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >等待文件存在

等待文件存在
EN

Stack Overflow用户
提问于 2017-01-04 19:18:15
回答 0查看 1.9K关注 0票数 0

我已经用WebApi2编写了一组web服务,它们最终调用一个CMD程序,该程序启动一个XML客户端,传递一个格式化的OpenEdge字符串,然后通过调用一个.p过程将记录插入到OpenEdge Progress数据库中(WebSpeed不是一个选项)。

.P文件有一组针对Progress应用程序运行的业务逻辑。它随后在完成时生成一个包含< Error >节点的XML文件。如果这个节点是空的,那么它就工作了。如果文件不存在或节点包含文本...它失败了。然后,我读取这个XML文件,并将< Error >节点的内容传递回Web Api中的客户机。

此时,从调用CMD/Progress小应用程序到尝试读取XML文件有10秒的静态延迟,以给予服务器运行.P文件和创建所述XML文件的时间。然而,这并不是很好,偶尔会向客户端返回一个错误,因为它找不到文件,然而,由于异常高的服务器负载,该文件是在响应返回后1秒创建的。或者,人们被迫等待10秒,而响应本可以在2秒内处理。

我需要想出一种“检查直到文件存在”的方法,直到超时时间过去。我做了一些研究,但找不到任何适合Web Api环境的东西。有人有什么建议吗?

下面的代码-请原谅我。我已经学到了很多,因为我一直在学习,并且对此非常陌生!

控制器

代码语言:javascript
复制
// the request date/time
DateTime requestDate = DateTime.Now;
// list of validation errors
List<string> ohValidation = new List<string>();

..。

代码语言:javascript
复制
WebExtensions.callInsertProgram(xml, "JOBLOG");
ohValidation =     XmlExtensions.ReadProgressXmlFileWithArray(job.logjob.placeref, requestDate, "joblogging");

CallInsertProgram

代码语言:javascript
复制
   public static void callInsertProgram(string xml, string program)
    {

        try
        {
            using (Process p = new Process())
            {
                p.StartInfo.FileName = @"C:\Rubixx\runProgress.exe";
                p.StartInfo.WorkingDirectory = @"C:\Rubixx";
                // stop windows from appearing on the server
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                // set the arguments for running. The program name and xml are passed in as arguments
                // wrapped in escaping "\" to stop spaces from being treated as a separator
                p.StartInfo.Arguments = "\"" + program + "," + xml + "\"";
                p.Start();
            }
        }
        catch (Exception e)
        {
            throw new OpenHousingException(e.Message.ToString());
        }

    }

ReadProgressXMLWithArray

代码语言:javascript
复制
public static List<string> ReadProgressXmlFileWithArray(string reference, DateTime requestDateTime, string folder)
    {
        // new empty list
        List<string> output 
            = new List<string>();

        // wait X seconds before doing anything 
        // to ensure the XML file has time to be created
        Delay_Start(fileDelay);

        // 
        string filename = fullFileName(jobno, folder, requestDateTime);
        string filepath = getFullFilepath(filename, folder);
        if (checkXmlFileExists(filepath))
        {
            // if so check for the existence of an error message
            output = getXmlErrorArray(filepath);
        }
        else
        {
            // if no file is found - the call to Progress hasn't executed. So tell the end user.
            throw new OpenHousingException("No OpenHousing file could be found");
        }

        return output;
    }

Delay_Start

代码语言:javascript
复制
    private static void Delay_Start(int Seconds)
    {
        DateTime StartTime;
        DateTime EndTime;

        StartTime = DateTime.Now;
        EndTime = StartTime.AddSeconds(Seconds);

        do
        { StartTime = DateTime.Now; } while (StartTime < EndTime);
    }

FullFileName (需要,因为在创建之前我不能确定XML文件名。文件格式为UniqueReference_DateTimeFileCreated.xml (xxxxxxxx_20160401-1100.xml),因此,我必须使用通配符搜索具有唯一引用的文件夹。

代码语言:javascript
复制
    public static string fullFileName(string jobNo, string folder, DateTime createdDate)
    {
        string fileName = string.Empty;
        string folderPath = fileLocation + folder;
        DirectoryInfo dir = new DirectoryInfo(folderPath);
        FileInfo[] files = dir.GetFiles(jobNo + "*", SearchOption.TopDirectoryOnly).Where(f => f.CreationTimeUtc > createdDate || f.LastWriteTimeUtc > createdDate).ToArray() ;
        foreach (var item in files)
        {
            fileName = item.Name;
        }

        if (string.IsNullOrEmpty(fileName))
            throw new OpenHousingException("No OpenHousing file could be found");

        return fileName;
    }

GetFullFilePath (可以整合到fullFileName中)

代码语言:javascript
复制
    private static string getFullFilepath(string filename, string folder)
    {
        return fileLocation + folder + @"\" + filename;
    }

CheckXMLFileExists

代码语言:javascript
复制
    private static bool checkXmlFileExists(string filepath)
    {
        bool fileExists = false;

        if (File.Exists(filepath))
        {
            fileExists = true;
        }

        return fileExists;
    }

GetXMLErrorArray

代码语言:javascript
复制
    private static List<string> getXmlErrorArray(string filepath)
    {

        List<string> output
            = new List<string>();

        // read the text from XML file
        using (TextReader txtReader = new StreamReader(filepath))
        {
            XmlSerializer xs
                = new XmlSerializer(typeof(JobError));

            // de-serialise the xml text
            // to a strongly typed object
            JobError result = (JobError)xs.Deserialize(txtReader);

            // if the xml file contains an error - return it to the client
            if (!string.IsNullOrEmpty(result.ErrorText))
                output.Add(result.ErrorText);

            //check for SoR errors that are created under a different node
            if (result.LineError != null)
            {
                List<LineError> lineErrs = result.LineError.ToList();

                foreach (LineError le in lineErrs)
                {
                    output.Add(le.SorCode + ":" + le.Error);
                }
            }
        }

        return output;

    }
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41462533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档