FileNotFoundException随机抛出

本文关键字:随机 FileNotFoundException | 更新日期: 2023-09-27 18:16:49

我正在开发一个c#工具,可以从未格式化的SD卡读取8gb的十六进制数据。

可以这样做,但是它会随机抛出File Not Found Exception。例如,它将读取1或2 gb,然后抛出它。其他时候,它会连续读取所有8 gb几次,然后抛出异常。换句话说,它似乎完全是随机弹出的。

我不知道是什么原因引起的。

编辑:我已经使用反馈来调整一些事情。下面粘贴的是更新后的代码。

它仍然随机抛出filenotfoundexception,但它现在总是抛出一个参数异常,当它试图读取mb 432的gig 8(如果它没有随机抛出filenotfound)。

报错文件句柄不支持同步操作。

class Program
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
      uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
      uint dwFlagsAndAttributes, IntPtr hTemplateFile);
    static void Main(string[] args)
    {
        string testOutputDirectory = @"C:''Users''aiovanna''Desktop''out1.txt"; //Specifies where to write the results of the read.
        try
        {
            SafeFileHandle fileHandle = CreateFile("''''.''E:", 0x80000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero);
            FileStream readStream = new FileStream(fileHandle, FileAccess.Read); //The stream to be read. Is converted to binary.
            BufferedStream bufStream = new BufferedStream(readStream, 1048576);
            FileStream writeStream = File.OpenWrite(testOutputDirectory); //Writing stream opened at the specified directory of output.
            //BinaryReader reader = new BinaryReader(readStream); //Changes the read stream to binary. Has more powerful methods.
            long gigsRead; //Loop counter that specifies the number of gigabytes read thus far.
            long megsRead; //Loop counter that specifies the number of megabytes read thus far within the current gigabyte.
            Stopwatch totalStopwatch = new Stopwatch(); //Stopwatch to time the total execution of the card read.
            Stopwatch megStopwatch = new Stopwatch(); //Stopwatch to time the execution of reading the current megabyte.
            Stopwatch gigStopwatch = new Stopwatch(); //Stopwatch to time the executation of reading the current gigabyte. 
            totalStopwatch.Start(); //Start timing the program. 
            int bytesRead; 
            for (gigsRead = 0; gigsRead < 8; gigsRead++) //Gigabyte loop
            {
                gigStopwatch.Start(); //Start timer for current gigabyte. 
                for (megsRead = 0; megsRead < 1024; megsRead++) //Megabyte loop
                {
                    megStopwatch.Start(); //Start timer for current megabyte. 
                    try
                    {
                        byte[] buffer = new byte[1048576]; //Buffer to be read into from card
                        long test = gigsRead * 1073741824 + megsRead * 1048576;
                        bufStream.Position = test;
                        bytesRead = bufStream.Read(buffer, 0, 1048576); //Read from SD card to buffer
                        if (bytesRead < 1048576)
                        {
                            Console.WriteLine("Didn't read whole chunk!");
                        }
                        writeStream.Write(buffer, 0, 1048576); //Write from buffer to output text file.
                        megStopwatch.Stop(); //Stop timer for current megabyte. 
                        Console.WriteLine("Finished mb {0} of gig {1} in {2}", megsRead + 1, gigsRead + 1, megStopwatch.Elapsed);
                        megStopwatch.Reset(); //Reset for next megabyte. 
                    }
                    catch (System.IO.FileNotFoundException ex)
                    {
                        System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
                        System.Console.WriteLine("Message: {0}", ex.Message);
                        System.Console.WriteLine("Source: {0}", ex.Source);
                        System.Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                        System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
                        System.Console.WriteLine(ex.ToString());
                        writeStream.Close(); //Close writing stream.
                        //reader.Close(); //Close the binary reader stream.
                        bufStream.Close();
                        fileHandle.Close(); //Close the SD card file.
                        readStream.Close(); //Close the filestream reader.
                        System.Console.WriteLine("You will need to turn off your computer, take out the card, turn the computer back on, put the SD card back in, and re-run the program.");
                        System.Console.WriteLine("Press any key to terminate.");
                        System.Console.ReadKey();
                        System.Environment.Exit(1);
                    }
                    catch (System.ArgumentException ex)
                    {
                        System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
                        System.Console.WriteLine("Message: {0}", ex.Message);
                        System.Console.WriteLine("Param Name: {0}", ex.ParamName);
                        System.Console.WriteLine("Source: {0}", ex.Source);
                        System.Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                        System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
                        System.Console.WriteLine(ex.ToString());
                        writeStream.Close(); //Close writing stream.
                        //reader.Close(); //Close the binary reader stream.
                        fileHandle.Close(); //Close the SD card file.
                        readStream.Close(); //Close the filestream reader.
                        System.Console.WriteLine("You will need to turn off your computer, take out the card, turn the computer back on, put the SD card back in, and re-run the program.");
                        System.Console.WriteLine("Press any key to terminate.");
                        System.Console.ReadKey();
                        System.Environment.Exit(1);
                    }
                }
                gigStopwatch.Stop(); //Stop timer for current gigabyte. 
                Console.WriteLine("Finished gig {0} in {1}", gigsRead + 1, gigStopwatch.Elapsed);
                gigStopwatch.Reset(); //Reset for next gigabyte. 
            }
            totalStopwatch.Stop(); //Stop total execution timer.
            Console.WriteLine(totalStopwatch.Elapsed); //Print total execution timer.
            writeStream.Close(); //Close writing stream.
            //reader.Close(); //Close the binary reader stream.
            writeStream.Close(); //Close writing stream.
            fileHandle.Close(); //Close the SD card file.
            readStream.Close(); //Close the filestream reader.
            bufStream.Close();
        }
        catch (System.IO.IsolatedStorage.IsolatedStorageException ex)
        {
            System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
            System.Console.WriteLine("Isolated Storage Exception");
            System.Console.WriteLine("Data: {0}", ex.Data);
            System.Console.WriteLine("Help Link: {0}", ex.HelpLink);
            System.Console.WriteLine("Inner Exception: {0}", ex.InnerException);
            System.Console.WriteLine("Message: {0}", ex.Message);
            System.Console.WriteLine("Source: {0}", ex.Source);
            System.Console.WriteLine("Stack Trace {0}", ex.StackTrace);
            System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
            Console.ReadKey();
        }
        catch (System.ArgumentException ex)
        {
            System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
            System.Console.WriteLine("Argument Exception");
            System.Console.WriteLine("Data: {0}", ex.Data);
            System.Console.WriteLine("Help Link: {0}", ex.HelpLink);
            System.Console.WriteLine("Inner Exception: {0}", ex.InnerException);
            System.Console.WriteLine("Message: {0}", ex.Message);
            System.Console.WriteLine("Param Name: {0}", ex.ParamName);
            System.Console.WriteLine("Source: {0}", ex.Source);
            System.Console.WriteLine("Stack Trace {0}", ex.StackTrace);
            System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
            Console.ReadKey();
        }
        catch (System.IO.DirectoryNotFoundException ex)
        {
            System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
            System.Console.WriteLine("Directory Not Found Exception");
            System.Console.WriteLine("Data: {0}", ex.Data);
            System.Console.WriteLine("Help Link: {0}", ex.HelpLink);
            System.Console.WriteLine("Inner Exception: {0}", ex.InnerException);
            System.Console.WriteLine("Message: {0}", ex.Message);
            System.Console.WriteLine("Source: {0}", ex.Source);
            System.Console.WriteLine("Stack Trace {0}", ex.StackTrace);
            System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
            System.Console.ReadKey();
        }
        catch (System.ObjectDisposedException ex)
        {
            System.Console.WriteLine("The error was: {0}", Marshal.GetLastWin32Error());
            System.Console.WriteLine("Object Disposed Exception");
            System.Console.WriteLine("Data: {0}", ex.Data);
            System.Console.WriteLine("Help Link: {0}", ex.HelpLink);
            System.Console.WriteLine("Inner Exception: {0}", ex.InnerException);
            System.Console.WriteLine("Message: {0}", ex.Message);
            System.Console.WriteLine("Object Name {0}", ex.ObjectName);
            System.Console.WriteLine("Source: {0}", ex.Source);
            System.Console.WriteLine("Stack Trace {0}", ex.StackTrace);
            System.Console.WriteLine("Target Site: {0}", ex.TargetSite);
            Console.ReadKey();
        }
    }
}

下面我重写了filenotfoundexception显示的错误:

消息:无法找到指定的文件。来源:mscorlib堆栈跟踪:在System.IO.__Error。WinIOError(int32 errorcode, String maybeFullPath)在System.IO.FileStream。ReadCore(Byte[] buffer, int32 offset, int32 count)在System.IO.FileStream。读取(Byte[] array, Int32偏移量,Int32计数)在System.IO.BinaryReader。读取(Byte[] buffer, Int32索引,Int32计数)在RawSDAccessTest.Program。Main(String{} args) in c:' users 'etc…在第67行目标站点:无效WinIOError(Int32, System.String)System.IO.FileNotFoundException:无法找到指定的文件。第67行是:读者。Read(buffer, 0, 1048576);

我发现这里真正奇怪的是,程序对第65行完全没问题,它也使用了reader对象。在执行第65行和67行之间,它决定该文件不再存在。我在中间等了一会儿,看看能不能解决问题。没有。

有什么想法可能导致它随机抛出这个异常,或者如何解决它?

EDIT: Process Monitor显示以下

8:40:26.1077157 AM SDCardReadAttempt3.vshost.exe 2432 ReadFile E: SUCCESS Offset: 3,228,565,504, Length: 1,048,576, I/O Flags:非缓存,优先级:Normal

8:40:26.1745974 AM SDCardReadAttempt3.vshost.exe 2432 ReadFile E: NO SUCH DEVICE Offset: 3,229,614,080, Length: 131,072, I/O Flags: Non-cached, Priority: Normal

所以在读取之间,设备不再存在。我将文件的创建和删除操作移到了内部循环中,这样每当它试图读取文件时就会创建文件。问题依然存在。闻起来像硬件。

编辑2:现在它偶尔抛出一个异步读异常。

9:16:16.1129926 AM SDCardReadAttempt3.vshost.exe 3752 ReadFile E: INVALID PARAMETER Offset: 7,969,177,600, Length: 1,048,576, I/O Flags: noncached, Priority: Normal

我不知道。net到底是怎么运作的。当文件没有被打开供多个线程读取时,它可能会将其变成一个线程进程。我把等待放回去看看是否能消除这个错误,这样我就能回到原来的那个。

FileNotFoundException随机抛出

我也遇到过类似的问题。我最终不得不捕获异常,等待一段时间(250毫秒对于我的目的来说很好),然后再次尝试重新读取相同的数据。我定义了一个阈值(6对我来说很好),在这一点上我放弃并向用户抛出一个错误。

在大多数情况下,这似乎给了硬件足够的时间来赶上。

同样,试着只读给你带来麻烦的那块。如果在读取特定块时总是出现错误,那么显然是硬件出了问题。

这可能是一个很长的镜头,但你试过ReadAsync方法吗?
http://msdn.microsoft.com/en-us/library/hh137813.aspx