Mono中的C#FileStream-违反文件共享 [英] C# FileStream in Mono - File sharing violation

查看:102
本文介绍了Mono中的C#FileStream-违反文件共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带有Mono的Raspbian上运行一个C#WinForms应用程序.它有一个计时器.当OnTimedEvent触发时,我检查我是否对要上传的文件具有独占访问权(以确保已完成将其写入磁盘),然后尝试上传.如果上传成功,则将文件移至存档文件夹,否则将其保留在那里并等待下一个计时器事件.连接到Internet时没有问题,但是当我测试没有并且上传失败时,第二个OnTimedEvent在检查同一文件是否准备就绪时再次发生异常.我得到了:

I have a C# WinForms application running on Raspbian with Mono. It has a timer. When the OnTimedEvent fires, I check if I have exclusive access to a file that I want to upload (to make sure it is finished being written to disk), then attempt to upload. If the upload is successful, I move the file to an archive folder, otherwise I leave it there and wait for the next timer event. I have no problems when connected to the Internet, but when I test without and my upload fails, the second OnTimedEvent gets an exception when checking if the same file is ready (again). I am getting :

Error message: ***Sharing violation on path 'path'
***HResult: ***-2147024864

检查文件是否准备就绪的方法:

Method to check if file is ready:

 public static bool IsFileReady(string filename)
    {

        // If the file can be opened for exclusive access it means that the file
        // is no longer locked by another process.
        try
        {
            var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);

            bool test = inputStream.Length > 0;

            inputStream.Close();
            inputStream.Dispose();

            return test;
        }
        catch (Exception e)
        {
            //log
            throw e;
        }
    }

这是在OntimedEvent上执行的操作:

This is what executes on the OntimedEvent:

            var csvFiles = from f in di.GetFiles()
                        where f.Extension == ".csv"
                        select f;  //get csv files in upload folder

            foreach (var file in csvFiles)
            {
                if (IsFileReady(file.FullName))  //check that file is done writing before trying to move.
                {
                    bool IsUploadSuccess = await WritingCSVFileToS3Async(file);//.Wait();  //upload file to S3

                    if (IsUploadSuccess)
                    {
                        File.Move(file.FullName, archivePath + file.Name);  //move to completed folder if upload successful. else, leave there for next upload attempt
                    }
                }
            }

据我了解,当第二个事件触发时,我的第一个FileStream(File.Open)似乎仍然锁定了文件.但是,我已经向IsFileReady方法中添加了.Close()和.Dispose(),但这似乎不起作用.

From what I can understand, it looks like my first FileStream (File.Open) still has the file locked when the 2nd event fires. However, I've added .Close() and .Dispose() to the IsFileReady method but that doesn't seem to be working.

任何帮助将不胜感激!

以下是WritingCSVFileToS3Async方法.

Below is the WritingCSVFileToS3Async method.

static async Task<bool> WritingCSVFileToS3Async(FileInfo file)
    {
        try
        {
            client = new AmazonS3Client(bucketRegion);

            // Put the object-set ContentType and add metadata.
            var putRequest = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = file.Name,
                FilePath = file.FullName ,
                ContentType = "text/csv"
            };
            //putRequest.Metadata.Add("x-amz-meta-title", "someTitle"); //don't need meta data at this time

            PutObjectResponse response = await client.PutObjectAsync(putRequest);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                return true;
            else
                return false;
        }
        catch (AmazonS3Exception e)
        {
            ErrorLogging.LogErrorToFile(e);
            return false;
        }
        catch (Exception e)
        {
            ErrorLogging.LogErrorToFile(e);
            return false;
        }

此外,我在Windows上运行了相同的应用程序,并且遇到了类似的异常:

Also, I ran the same application on Windows, and am getting a similar exception:

The process cannot access the file 'path' because it is being used by another process.

推荐答案

我相信我已经找到了问题.我注意到我没有为PUT请求捕获客户端超时异常(未连接到Internet).我的计时器间隔是20秒,比S3客户端超时(30秒)短.因此,在第二个计时器事件触发时,客户端仍将文件捆绑在一起,从而导致访问冲突.我将计时器间隔增加到60秒,现在可以捕获客户端超时异常,并且可以在下一个计时器事件之前进行处理.

I believe I've found the problem. I noticed that I was not catching the client timeout exception for the PUT request(not connected to internet). My timer interval was 20 seconds, which is shorter than the S3 client timeout (30 seconds). So the client still had the file tied up by the time the second timer event fired, hence the access violation. I increased the timer interval to 60 seconds, and I now catch the client timeout exception and can handle it before the next timer event.

感谢您的帮助.

这篇关于Mono中的C#FileStream-违反文件共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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