即使包含在Using子句中,C#StreamWriter也不会释放对文件的锁定 [英] C# StreamWriter not releasing lock on a file even when including within Using clause

查看:234
本文介绍了即使包含在Using子句中,C#StreamWriter也不会释放对文件的锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#.Net代码将包含xml数据的文件复制到linux服务器上的某个位置。我复制文件后不久,我调用了第三方(Java app)网络服务,试图使用复制的文件。第三方服务首先尝试重命名该文件,并在此过程中遇到问题 - Java File.renameTo方法返回false 。这表明该文件仍被其他进程使用/打开。



流编写代码如下:



 使用(StreamWriter file =  new  StreamWriter(filename )
{
file.WriteLine(xml);
file.Close();
}





//调用Web服务的代码如下:


复制的文件可能很大(在某些情况下为20-30 MB)。有没有办法我们可以完全确认文件已被完全复制到该位置,并且在我调用第三方服务之前没有进程保留该文件。我相信除了一个复制之外没有其他进程保留文件。

解决方案

 打开文件 in 你的应用程序使用 FileStream 任何类似的选项  打开它 in  SharingMode  如果你打开它  SharingMode文件将被锁定。 如果在非共享模式下打开,文件将被锁定。 

知道 if 您正在寻找


I using C#.Net code to copy a file containing xml data to a location which is on a linux server. Soon after i copy the file i call a third party (java app) web-service that tries to consume the file copied. The third party service first tries to rename the file and in the process is getting an issue -Java File.renameTo method returns false. This suggests that the file is still being used/open by some other process.

The stream write code is given below

using (StreamWriter file = new StreamWriter(filename)
                {
                    file.WriteLine(xml);
                    file.Close();
                }



// Code that calls the web service follows

The file that is copied may be huge in size (20-30 MB in some cases). Is there any way we can fully confirm that the file has been completely copied to the location and that no process is holding on to the file before i call the third party service. I am sure there not other process holding on other than the one copying the file.

解决方案

When you open the file in your application using FileStream or any similar class you have option of opening it in SharingMode or not. If you open it in SharingMode file will not be locked. If you open it in Non-Sharing mode, file will be locked.

Let me know if that is what you were looking for.


这篇关于即使包含在Using子句中,C#StreamWriter也不会释放对文件的锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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