【发布时间】:2014-11-19 03:01:06
【问题描述】:
谁能告诉我如何摆脱这个错误
该进程无法访问该文件,因为它正被另一个进程使用
这是我的代码
if (!File.Exists(FlagFilePath))
{
Debug.WriteLine("Trying to download sales data file ");
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = ConfigurationManager.AppSettings["SFTPDomain"],
UserName = ConfigurationManager.AppSettings["SFTPUser"],
Password = ConfigurationManager.AppSettings["SFTPPass"],
PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["SFTPPortNumber"]),
GiveUpSecurityAndAcceptAnySshHostKey = true,
};
using (Session session = new Session())
{
//Attempts to connect to your SFtp site
session.Open(sessionOptions);
//Get SFtp File
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary; //The Transfer Mode - Automatic, Binary, or Ascii
transferOptions.FilePermissions = null; //Permissions applied to remote files;
transferOptions.PreserveTimestamp = false; //Set last write time of destination file
//to that of source file - basically change the timestamp to match destination and source files.
transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
//SFTP File Path
Sftp_RemotePath = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
//Delete File if Exist
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}
//the parameter list is: remote Path, Local Path with filename
TransferOperationResult transferOperationResult = session.GetFiles(Sftp_RemotePath, FilePath , false, transferOptions);
//Throw on any error
transferOperationResult.Check();
Debug.WriteLine("Downloaded fresh sales data file!");
}
}
我正在使用 MVC 并且有两个可以访问此类的控制器。当我一次运行一个控制器时,它工作正常,但是当我同时运行两个控制器时,我在其中一个控制器中收到此错误:
WinSCP.SessionRemoteException: Can't create file 'D:\TESTING\SFTP\Data.csv'. ---> WinSCP.SessionRemoteException: System Error.
Code: 32.
The process cannot access the file because it is being used by another process
--- End of inner exception stack trace ---
at WinSCP.OperationResultBase.Check()
at JetStarAPI.Models.SFTPClient.DownloadFile(String FilePath) in D:\TESTING\SFTP\Models\SFTPClient.cs:line 65}
我在这行之后收到此错误
transferOperationResult.Check();
如果我在这里更改文件名
TransferOperationResult transferOperationResult = session.GetFiles(Sftp_RemotePath, FilePath+Path.GetRandomFileName() , false, transferOptions);
它工作正常并使用随机文件名保存文件,但我想传递我的文件名。如何解决?
【问题讨论】:
-
您需要确保您没有在您的代码或其他应用程序中打开该文件。谷歌搜索这个错误会出现一大堆例子。
-
它适用于单个请求,但是当我同时击中两个控制器时,我会收到此错误,这是行 TransferOperationResult transferOperationResult = session.GetFiles(Sftp_RemotePath, FilePath, false, transferOptions);当我将 FilePath 更改为 FilePath+Path.GetRandomFileName() 时,它可以工作
-
是的,因为一个控制器已经打开并锁定了文件,而另一个尝试同时打开它,导致了这个异常。实际上,您尝试打开文件两次。您的 GetRandomFileName 有效,因为每个控制器从该方法接收到不同的结果,因此每个控制器都访问不同的文件。
-
那我该怎么解决呢?
标签: c# .net winscp winscp-net