Browse Source

Prevent crashes when list is empty

Ruben 4 years ago
parent
commit
8c2717a36a
1 changed files with 28 additions and 11 deletions
  1. 28 11
      PicView/ChangeImage/History.cs

+ 28 - 11
PicView/ChangeImage/History.cs

@@ -21,10 +21,20 @@ namespace PicView.ChangeImage
             fileHistory = new List<string>();
 
             string path = FileFunctions.GetWritingPath() + "\\Recent.txt";
+            StreamReader? listToRead = null;
 
             if (File.Exists(path))
             {
-                var listToRead = new StreamReader(path);
+                try
+                {
+                    listToRead = new StreamReader(path);
+                }
+                catch (System.Exception)
+                {
+                    return; // Putting in try catch prevents error when file list is empty
+                }
+
+                if (listToRead == null) { return; }
 
                 using (listToRead)
                 {
@@ -50,19 +60,26 @@ namespace PicView.ChangeImage
                 fileHistory = new List<string>();
             }
 
-            // Create file called "Recent.txt" located on app folder
-            var streamWriter = new StreamWriter(FileFunctions.GetWritingPath() + "\\Recent.txt");
+            try
+            {
+                // Create file called "Recent.txt" located on app folder
+                var streamWriter = new StreamWriter(FileFunctions.GetWritingPath() + "\\Recent.txt");
+
+                foreach (string item in fileHistory)
+                {
+                    // Write list to stream
+                    streamWriter.WriteLine(item);
+                }
 
-            foreach (string item in fileHistory)
+                // Write stream to file
+                streamWriter.Flush();
+                // Close the stream and reclaim memory
+                streamWriter.Close();
+            }
+            catch (System.Exception)
             {
-                // Write list to stream
-                streamWriter.WriteLine(item);
+                // Putting in try catch prevents error when file list is empty
             }
-
-            // Write stream to file
-            streamWriter.Flush();
-            // Close the stream and reclaim memory
-            streamWriter.Close();
         }
 
         internal static async Task OpenLastFileAsync()