简体   繁体   中英

Odd file does not exist error

I'm running into an error that I can't catch and it should not be there.

if (System.IO.File.Exists (PathToMyFile)) 
{
    try{
        FileStream fs = new FileStream(PathToMyFile, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
        myFile =Convert.ToBase64String  (bytes) ;
        }
    catch{}
    }

For some reason , sometimes I get a exception error that the file does not exist when It most definitely is there. The very first "If statement" even says it is there yet when trying to open the file I sometimes get a massive app crash that the catch does not "catch" .

Like I said, it's a random error, most of the time the code is perfect but the odd occasion seems to throw an error that the app stops working .

First thing is to make sure you close the file\\stream

So you can call fs.Close() or using

if (File.Exists(pathToMyFile))
{
   try
   {
      using (var fs = new FileStream(pathToMyFile, FileMode.Open, FileAccess.Read))
      {
         BinaryReader br = new BinaryReader(fs);
         Byte[] bytes = br.ReadBytes((Int32) fs.Length);
         br.Close();
         fs.Close();
         myFile = Convert.ToBase64String(bytes);
      }
   }
   catch
   {
      // Log exception
   }
}

Second, if you need to read the file as string, simply use

if (File.Exists(pathToMyFile))
{
   try
   {
      myFile = File.ReadAllText(pathToMyFile);
   }
   catch
   {
      // Log exception              
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM