C#consoleapplication抛出ioexception [英] C# consoleapplication throwing ioexception

查看:65
本文介绍了C#consoleapplication抛出ioexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#控制台应用程序。我正在尝试使用FileSystemWatcher观看usb文件活动,如果有任何文件更改已完成,则触发事件并将我的文件内容编码为base64格式并将其显示在console中。现在它显示IOException,如

进程无法访问F:\ MyService.InstallLogI,因为它正由另一个进程使用。





我尝试过:



  class 计划
{
静态 FileSystemWatcher观察者;
静态 void Main( string [] args)
{
var drives = DriveInfo.GetDrives();

foreach var drive 个驱动器中)
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(drive.Name);
watch(drive.Name);
}
}

}
静态 void watch( String 路径)
{

watcher = new FileSystemWatcher();

watcher.Path = path; // 指定要观看的路径
watcher.EnableRaisingEvents = true ; // make肯定观察者会在文件夹发生变化的情况下举起活动。
watcher.IncludeSubdirectories = true ; // 确保观察者也会查看子文件夹。
watcher.Filter = *。*; // 观察者应监控所有类型的文件。

watcher.Created + = watcher_Created; // 在指定路径中创建文件时要调用的注册事件
watcher.Changed + = watcher_Changed; // 在指定路径中更新文件时要调用的注册事件
watcher.Deleted + = watcher_Deleted; // 在指定路径中删除文件时要调用的注册事件

// watcher.Created + = new FileSystemEventHandler(watcher_Changed);


while true ); // 运行无限循环,所以程序不会终止,直到我们强制它。
}

静态 void watcher_Deleted( object sender,FileSystemEventArgs e)
{
Console.WriteLine( 文件: + e.FullPath + 已删除。);
}

静态 void watcher_Changed( object sender,FileSystemEventArgs e)
{
Console.WriteLine( 文件: + e.FullPath + 已更新。);

watcher.EnableRaisingEvents = false ;

尝试
{
if (!string .IsNullOrEmpty(e.FullPath))
{

FileStream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess 。读);
byte [] filebytes = new byte [fs.Length];
fs.Read(filebytes, 0 ,Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes,Base64FormattingOptions.InsertLineBreaks);
Console.WriteLine(encodedData);

// File.WriteAllText(e.FullPath,encodedData);


}

}
catch (例外情况除外)
{
Console.WriteLine(excep.Message.ToString());
// Thread.Sleep(100);
}


// watcher.EnableRaisingEvents = true;
}

静态 void watcher_Created( object sender,FileSystemEventArgs e)
{
Console.WriteLine( 文件: + e.FullPath + 已创建。);
// System.Windows.Forms.Clipboard.Clear();

}

}

解决方案

FileSystemWatcher会在文件发生变化时通知你但它不知道文件的编写者是否完成了它。当其他应用程序仍在进行更改时,可以报告更改!



您的代码必须尝试打开文件,如果失败,请稍等一下再试一次。如果您想要无限期地等待或者在经过一定的时间或尝试次数后放弃,这取决于您。


嗯...

< pre lang =C#> if (!string.IsNullOrEmpty(e.FullPath))
{
FileStream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess.Read);
byte [] filebytes = new byte [fs.Length];
fs.Read(filebytes, 0 ,Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes,Base64FormattingOptions.InsertLineBreaks);
Console.WriteLine(encodedData);
// File.WriteAllText(e.FullPath,encodedData);
}



你没有关闭文件 - 所以下次你试图访问它时,它仍然是打开的!它将不会被关闭,直到垃圾收集器被踢 - 下周,也许 - 在你之后清理。

尝试使用块:

  if (!string.IsNullOrEmpty(e.FullPath))
{
使用(FileStream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess.Read) )
{
byte [] filebytes = new 字节 [fs.Length];
fs.Read(filebytes, 0 ,Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes,Base64FormattingOptions.InsertLineBreaks);
Console.WriteLine(encodedData);
// File.WriteAllText(e.FullPath,encodedData);
}
}

当它超出范围时,它将被关闭和处置。


I've a c# console application. I am trying to watch a usb file activities using FileSystemWatcher, If there is any file change is done then the event is triggered and my file content will be encoded into base64 format and display it in console.Now its showing an IOException like

The process cannot access F:\MyService.InstallLogI because it is being used by another process.



What I have tried:

class Program
    {
        static FileSystemWatcher watcher;
        static void Main(string[] args)
        {
            var drives = DriveInfo.GetDrives();
            
            foreach (var drive in drives)
            {
                if (drive.DriveType == DriveType.Removable)
                {
                    Console.WriteLine(drive.Name);
                    watch(drive.Name);
                }
            }

        }
        static void watch(String path)
        {
            
            watcher = new FileSystemWatcher();

            watcher.Path = path;//assigning path to be watched
            watcher.EnableRaisingEvents = true;//make sure watcher will raise event in case of change in folder.
            watcher.IncludeSubdirectories = true;//make sure watcher will look into subfolders as well.
            watcher.Filter = "*.*"; //watcher should monitor all types of file.

            watcher.Created += watcher_Created; //register event to be called when a file is created in specified path
            watcher.Changed += watcher_Changed;//register event to be called when a file is updated in specified path
            watcher.Deleted += watcher_Deleted;//register event to be called when a file is deleted in specified path

           // watcher.Created += new FileSystemEventHandler(watcher_Changed);


            while (true) ;//run infinite loop so program doesn't terminate untill we force it.
        }

        static void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is deleted.");
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is updated.");

            watcher.EnableRaisingEvents = false;

            try
            {
                if (!string.IsNullOrEmpty(e.FullPath))
                {

                    FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read);
                    byte[] filebytes = new byte[fs.Length];
                    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
                    string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
                    Console.WriteLine(encodedData);

                    // File.WriteAllText(e.FullPath, encodedData);


                }

              }
            catch (Exception excep)
            {
                Console.WriteLine(excep.Message.ToString());
                //Thread.Sleep(100);
            }


            //watcher.EnableRaisingEvents = true;
        }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is created.");
           // System.Windows.Forms.Clipboard.Clear();

        }
 
    }

解决方案

The FileSystemWatcher will notify you when the file is changed but it has no idea if the writer of the file is done with it. Changes can be reported while the other application is still making them!

Your code has to try to open the file and if it fails, wait a bit and try again. It's up to you if you want to keep waiting indefinitely or just give up after a certain amount of time or number of tries.


Um...

if (!string.IsNullOrEmpty(e.FullPath))
    {
    FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read);
    byte[] filebytes = new byte[fs.Length];
    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
    string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
    Console.WriteLine(encodedData);
    // File.WriteAllText(e.FullPath, encodedData);
    }


You don't close the file - so the next time you try to access it, it's still open! It won't get closed until the Garbage collector gets kicked in - next week, maybe - to clean up after you.
Try a using block:

if (!string.IsNullOrEmpty(e.FullPath))
    {
    using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read))
        {
        byte[] filebytes = new byte[fs.Length];
        fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
        string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
        Console.WriteLine(encodedData);
        // File.WriteAllText(e.FullPath, encodedData);
        }
    }

And it will be Closed and Disposed when it goes out of scope.


这篇关于C#consoleapplication抛出ioexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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