System.IO.IOException message

MiPakTeh 1,476 Reputation points
2022-12-31T04:52:36.263+00:00

Hi All,
Sometimes when I run this code the Error raise.somebody show me which part code is error.

What to do;
Move the file created or renamed in the whole c:\ to d:\test11.
Code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;  
using System.IO;  
using System.Security.Permissions;  
using static System.IO.Path;  
using System.Threading;  
  
namespace WMI_  
{  
    public partial class Form1 : Form  
    {  
        private string TargetPath = @"d:\test11\";  
        private bool IsNewFile = false;  
        private List<ListViewItem> myCache = new List<ListViewItem>();  
  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        private void Form1_Load(object sender, EventArgs e)  
        {  
            listView1.View = View.Details;  
            listView1.GridLines = true;  
            listView1.VirtualMode = true;  
            listView1.RetrieveVirtualItem += ListView1_RetrieveVirtualItem;  
            listView1.Columns.Add("Filename", 600);  
            var watcher = new FileSystemWatcher(@"c:\");  
            watcher.NotifyFilter = NotifyFilters.Attributes  
                                 | NotifyFilters.CreationTime  
                                 | NotifyFilters.DirectoryName  
                                 | NotifyFilters.FileName  
                                 | NotifyFilters.LastAccess  
                                 | NotifyFilters.LastWrite  
                                 | NotifyFilters.Security  
                                 | NotifyFilters.Size;  
            watcher.Created += OnCreated;  
            watcher.Renamed += OnRenamed;  
            watcher.Error += OnError;  
            //watcher.Filter = "*.txt";  
            watcher.IncludeSubdirectories = true;  
            watcher.EnableRaisingEvents = true;  
        }  
  
        private void ListView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)  
        {  
            if (myCache.Count > 0)  
            {  
                e.Item = myCache[e.ItemIndex];  
            }  
        }  
  
        private string newFilePath;  
        private void OnCreated(object sender, FileSystemEventArgs e)  
        {  
            newFilePath = e.FullPath;  
            IsNewFile = true;  
        }  
                private static void OnError(object sender, ErrorEventArgs e) => DisplayException(e.GetException());  
         /// <summary>  
         /// For debug purposes  
         /// For a production environment write to a log file  
         /// </summary>  
         /// <param name="ex"></param>  
         private static void DisplayException(Exception ex)  
         {  
             if (ex != null)  
             {  
                 Debug.WriteLine($"Message: {ex.Message}");  
                 Debug.WriteLine("Stacktrace:");  
                 Debug.WriteLine(ex.StackTrace);  
                 Debug.WriteLine("");  
      
                 DisplayException(ex.InnerException);  
             }  
         }  
        private void OnRenamed(object sender, RenamedEventArgs e)  
        {  
  
            if (IsNewFile && e.OldFullPath == newFilePath)  
            {  
                FileInfo fileInfo = new FileInfo(e.FullPath);  
                string TargetFile = Path.Combine(TargetPath, fileInfo.Name);  
  
                using (StreamWriter fileV = new System.IO.StreamWriter(e.FullPath))  
                {  
                    foreach (var sfile in e.FullPath)  
                    {  
                        fileV.WriteLine(sfile);  
                    }  
                }  
                if (File.Exists(TargetFile))  
                {  
                    File.Delete(TargetFile);  
                }  
  
                //The File.Delete process may not end in time, causing File.Move to be abnormal, indicating that the file is being used.                   
                Thread.Sleep(100);  
                File.Move(e.FullPath, TargetFile);  
                myCache.Add(new ListViewItem() { Text = TargetFile });  
                this.Invoke((MethodInvoker)delegate ()  
                {  
                    listView1.VirtualListSize = myCache.Count;  
                });  
            }  
        }  
    }  
}  
  
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. MiPakTeh 1,476 Reputation points
    2023-01-02T09:25:12.603+00:00

    275374-capture.png


  2. MiPakTeh 1,476 Reputation points
    2023-01-02T12:28:28.193+00:00

    System.IO.IOException
    HResult=0x80070020
    Message=The process cannot access the file because it is being used by another process.
    Source=mscorlib
    StackTrace:
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    at System.IO.__Error.WinIOError()
    at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
    at System.IO.File.Move(String sourceFileName, String destFileName)
    at WMI_.Form1.OnRenamed(Object sender, RenamedEventArgs e) in C:\Users\family\source\repos\WMI_\WMI_\Form1.cs:line 122
    at System.IO.FileSystemWatcher.OnRenamed(RenamedEventArgs e)
    at System.IO.FileSystemWatcher.NotifyRenameEventArgs(WatcherChangeTypes action, String name, String oldName)
    at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

    This exception was originally thrown at this call stack:
    System.IO.__Error.WinIOError(int, string)
    System.IO.__Error.WinIOError()
    System.IO.File.InternalMove(string, string, bool)
    System.IO.File.Move(string, string)
    WMI_.Form1.OnRenamed(object, System.IO.RenamedEventArgs) in Form1.cs
    System.IO.FileSystemWatcher.OnRenamed(System.IO.RenamedEventArgs)
    System.IO.FileSystemWatcher.NotifyRenameEventArgs(System.IO.WatcherChangeTypes, string, string)
    System.IO.FileSystemWatcher.CompletionStatusChanged(uint, uint, System.Threading.NativeOverlapped*)
    System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint, uint, System.Threading.NativeOverlapped*)


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.