2

エラーをなくす方法を誰か教えてください

ファイルが別のプロセスによって使用されているため、プロセスはファイルにアクセスできません

これが私のコードです

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 を使用しており、このクラスにアクセスする 2 つのコントローラーがあります。コントローラーを 1 つずつ実行すると正常に動作しますが、両方のコントローラーを一緒に実行すると、コントローラーの 1 つでこのエラーが発生します。

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);

正常に動作し、ランダムなファイル名でファイルを保存しますが、FileName を渡したいです。これを解決するには?

4

1 に答える 1

0
static bool IsDownloadInProgress = false;

    public static string DownloadFile(string FilePath)
    {

        string SalesStatus = "ok";
        try
        {

            if (!File.Exists(FlagFilePath) &&  !IsDownloadInProgress)
            {
                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.On;
                    //SFTP File Path
                    Sftp_RemotePath = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
                    //Delete File if Exist
                    if (System.IO.File.Exists(FilePath))
                    {
                        System.IO.File.Delete(FilePath);
                    }
  //Throw on any error 
                   session.FileTransferred += OnFileTransferComplete;
                   IsDownloadInProgress = true;

                    //the parameter list is: remote Path, Local Path with filename 
                //    string result = Path.GetRandomFileName();
                   session.GetFiles(Sftp_RemotePath,FilePath,false,  transferOptions).Check();


                    session.Dispose();
                  //  File.Move(FilePath, "foo2.png");
                    Debug.WriteLine("Downloaded fresh sales data file!");
                }
            }
        }

        catch (Exception ex)
        {

            string _errorMsg = "";
            // Setting Sales Status values
            if (ex.InnerException != null)
            {
                if (ex.InnerException.Message.Contains("Authentication failed"))
                {
                    _errorMsg = ex.InnerException.Message;
                    Debug.WriteLine("wrong username/password");
                    SalesStatus = "2";
                }
                else if (ex.InnerException.Message.Contains("No such file or directory"))
                {
                    _errorMsg = ex.InnerException.Message;
                    Debug.WriteLine("File is not Available");
                    SalesStatus = "3";
                }
            }
            else
            {
                _errorMsg = ex.Message;
                Debug.WriteLine("General SFTP Error");
                SalesStatus = "4";
            }


            //Create log error file
            if (!File.Exists(FlagFilePath))
            {
                // create SFTP LocalErrorFlag
                Debug.WriteLine("Creating SFTP flag file");
                System.IO.File.WriteAllText(FlagFilePath, "SFTP Error: " + _errorMsg);
            }
            else
            {
                Debug.WriteLine("SFTP error Flag file already exists");
            }


        }
        return SalesStatus;
    }

    private static void OnFileTransferComplete(object sender, TransferEventArgs e)
    {
        IsDownloadInProgress = false;
        ((Session)sender).FileTransferred -= OnFileTransferComplete;
    }
于 2014-11-19T03:24:33.897 に答える