简体   繁体   English

该进程无法访问该文件,因为它正在被另一个进程使用

[英]The process cannot access the file because it is being used by another process

I am running a program where a file gets uploaded to a folder in IIS,and then is processed to extract some values from it. 我正在运行一个程序,文件被上传到IIS中的文件夹,然后被处理以从中提取一些值。 I use a WCF service to perform the process, and BackgroundUploader to upload the file to IIS. 我使用WCF服务执行该过程,并使用BackgroundUploader将文件上传到IIS。 However, after the upload process is complete, I get the error "The process cannot access the file x because it is being used by another process." 但是,上传过程完成后,出现错误“该进程无法访问文件x,因为它正在被另一个进程使用”。 Based on similar questions asked here, I gathered that the file concerned needs to be in a using statement. 基于此处提出的类似问题,我收集到相关文件需要放在using语句中。 I tried to modify my code to the following, but it didn't work, and I am not sure if it is even right. 我试图将我的代码修改为以下代码,但是它没有用,并且我不确定它是否正确。

namespace App17
{
public sealed partial class MainPage : Page, IDisposable
{
   private CancellationTokenSource cts;      

    public void Dispose()
    {
        if (cts != null)
        {
            cts.Dispose();
            cts = null;
        }

        GC.SuppressFinalize(this);
    }

    public MainPage()
    {
        this.InitializeComponent();
        cts = new CancellationTokenSource();
    }

    public async void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {               
            Uri uri = new Uri(serverAddressField.Text.Trim());
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();


            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                GlobalClass.filecontent = file.Name;
                GlobalClass.filepath = file.Path;
                BackgroundUploader uploader = new BackgroundUploader();
                uploader.SetRequestHeader("Filename", file.Name);
                UploadOperation upload = uploader.CreateUpload(uri, file);
                await HandleUploadAsync(upload, true);
                stream.Dispose();
            }


        }

        catch (Exception ex)
        {
            string message = ex.ToString();
            var dialog = new MessageDialog(message);
            await dialog.ShowAsync();
            Log(message);
        }

    }


   private void CancelAll(object sender, RoutedEventArgs e)
   {
       Log("Canceling all active uploads");
       cts.Cancel();
       cts.Dispose();
       cts = new CancellationTokenSource();
   }


   private async Task HandleUploadAsync(UploadOperation upload, bool start)
   {
       try
       {
           Progress<UploadOperation> progressCallback = new Progress<UploadOperation>(UploadProgress);
           if (start)
           {

               await upload.StartAsync().AsTask(cts.Token, progressCallback);
           }
           else
           {
               // The upload was already running when the application started, re-attach the progress handler.
               await upload.AttachAsync().AsTask(cts.Token, progressCallback);
           }

           ResponseInformation response = upload.GetResponseInformation();
           Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));

           cts.Dispose();
       }

       catch (TaskCanceledException)
       {
           Log("Upload cancelled.");
       }
       catch (Exception ex)
       {
           string message = ex.ToString();
           var dialog = new MessageDialog(message);
           await dialog.ShowAsync();
           Log(message);
       }
   }



   private void Log(string message)
   {
       outputField.Text += message + "\r\n";
   }


   private async void LogStatus(string message)
   {
       var dialog = new MessageDialog(message);
       await dialog.ShowAsync();
       Log(message);
   }


   private void UploadProgress(UploadOperation upload)
   {
       BackgroundUploadProgress currentProgress = upload.Progress;
       MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid,
           currentProgress.Status));
       double percentSent = 100;
       if (currentProgress.TotalBytesToSend > 0)
       {
           percentSent = currentProgress.BytesSent * 100 / currentProgress.TotalBytesToSend;
       }

       MarshalLog(String.Format(CultureInfo.CurrentCulture,
           " - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", currentProgress.BytesSent,
           currentProgress.TotalBytesToSend, percentSent, currentProgress.BytesReceived, currentProgress.TotalBytesToReceive));

       if (currentProgress.HasRestarted)
       {
           MarshalLog(" - Upload restarted");
       }

       if (currentProgress.HasResponseChanged)
       {

           MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);


       }
   }


   private void MarshalLog(string value)
   {
       var ignore = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
       {
           Log(value);
       });
   }


}

} }

After this is done, the file name is sent to a WCF service which will access and process the uploaded file to extract certain values. 完成此操作后,文件名将发送到WCF服务,该服务将访问并处理上载的文件以提取某些值。 It is at this point I receive the error. 这是我收到的错误。 I would truly appreciate some help. 我将非常感谢您的帮助。

public async void Extract_Button_Click(object sender, RoutedEventArgs e)
    {
      ServiceReference1.Service1Client MyService = new ServiceReference1.Service1Client();
      string filename = GlobalClass.filecontent;            
      string filepath = @"C:\Users\R\Documents\Visual Studio 2015\Projects\WCF\WCF\Uploads\"+ filename;
      bool x = await MyService.ReadECGAsync(filename, filepath);

    }

EDIT: Code before I added the using block 编辑:添加我的使用块之前的代码

     try
        {
            Uri uri = new Uri(serverAddressField.Text.Trim());
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();
            GlobalClass.filecontent = file.Name;
            GlobalClass.filepath = file.Path;
            BackgroundUploader uploader = new BackgroundUploader();
            uploader.SetRequestHeader("Filename", file.Name);
            UploadOperation upload = uploader.CreateUpload(uri, file);
            await HandleUploadAsync(upload, true);
        }

您还应该关闭文件写入磁盘的流(查看您的CreateUpload实现)。

When you work with stream writers you actually create a process, which you can close it from task manager. 与流编写器一起使用时,实际上是创建一个流程,您可以从任务管理器中关闭该流程。 And after stream.Dispose() put stream.Close(). 然后在stream.Dispose()之后放stream.Close()。

This should solve your problem. 这应该可以解决您的问题。

i got such error in DotNet Core 2 using this code: 我在使用以下代码的DotNet Core 2中遇到此类错误:

await file.CopyToAsync(new FileStream(fullFileName, FileMode.Create));
counter++;

and this is how I managed to get rid of message (The process cannot access the file x because it is being used by another process): 这就是我设法摆脱消息的方式(该进程无法访问文件x,因为它正在被另一个进程使用):

using (FileStream DestinationStream = new FileStream(fullFileName, FileMode.Create))
{
    await file.CopyToAsync(DestinationStream);
    counter++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 该进程无法访问文件.exe,因为它正在被另一个进程使用 - The process cannot access the file .exe because it is being used by another process 该进程无法访问&#39;xml&#39;文件,因为它正由另一个进程使用 - The process cannot access the 'xml' file because it is being used by another process 进程无法访问文件 <filepath> 因为它正在被另一个进程使用 - The process cannot access the file <filepath> because it is being used by another process 该进程无法访问该文件,因为该文件正在被另一个进程使用 - The process cannot access the file because it is being used by another process2 该进程无法访问该文件,因为该文件正由另一个进程使用 - The process cannot access the file because it is being used by another process 该进程无法访问该文件,因为它正在被另一个进程使用 - The process cannot access the file because it is being used by another process “进程无法访问该文件,因为该文件正在被另一个进程使用” - “Process cannot access the file because it is being used by another process” 该进程无法访问该文件,因为它正由另一个进程使用 - The process cannot access the file, because it is being used by another process 进程无法访问图像文件,因为它正在被另一个进程使用 - process cannot access the image file because it is being used by another process 错误:进程无法访问文件“...”,因为它正由另一个进程使用 - Error: The process cannot access the file '…' because it is being used by another process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM