文件系统文件夹的多个当前请求到处理文件C#XML

时间:2013-11-14 18:29:05

标签: c# .net xml windows-services

我的文件系统中存在一个文件夹,里面有很多XML文件。让我们说10,000。

我有多个(5)Windows服务每隔30秒检查一次该文件夹并同时处理文件。我正在尝试足够智能地编写服务流程代码,以便它可以处理并发的处理请求。

然而,它有时会挂在几个文件上。

E[The process cannot access the file '...' because it is being used by another process.]

我看到上面的错误在处理过程中记录了大约1%的文件。我该怎么做才能改进以下代码以防止这种情况发生?

class Program
{
    private static string _instanceGuid;
    static string InstanceGuid
    {
        get
        {
            if(_instanceGuid == null)
            {
                _instanceGuid =  Guid.NewGuid().ToString();
            }
            return _instanceGuid;
        }
    }

    static void Main(string[] args)
    {
        string[] sourceFiles = Directory.GetFiles("c\\temp\\source\\*.xml")
                                       .OrderBy(d => new FileInfo(d).CreationTime).ToArray();

        foreach (string file in sourceFiles)
        {
            var newFileName = string.Empty;

            try
            {
                // first we'll rename in this way try and 
                // i would think it should throw an exception and move on to the next file. an exception being thrown means that file should already be processing by another service. 

                newFileName = string.Format("{0}.{1}", file, InstanceGuid);
                File.Move(file, newFileName);

                var xml = string.Empty;
                using (var s = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                using (var tr = new StreamReader(s))
                {
                    xml = tr.ReadToEnd();
                }

                // at this point we have a valid XML save to db
            }
            catch (FileNotFoundException ex)
            {
                // continue onto next source file
            }
            catch (Exception ex)
            {
                // log error
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将“FileShare.None”替换为“FileShare.Read”,如下所示:

            using (var s = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.None))

http://msdn.microsoft.com/en-us/library/system.io.fileshare%28v=vs.110%29.aspx