Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated Helpers.cs tryReadFile method so that it handles exceptions that may happen, without crashing the program. #44

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 60 additions & 18 deletions dotnet/DWXConnect/api/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,27 +65,69 @@ public static void tryDeleteFile(string path)
}


/*Formats a double value to string.
Args:
value (double): numeric value to format.
*/
public static string format(double value)
/*Formats a double value to string.

Args:
value (double): numeric value to format.

*/
public static string format(double value)
{
return value.ToString("G", CultureInfo.CreateSpecificCulture("en-US"));
}

public static string tryReadFile(string path)
{
try
{
return File.ReadAllText(path);
}
catch
{
return "";
}
}
/*Tries to read a file and handles various exceptions which then return an empty string and writes the exception to the console.

*/
public static string tryReadFile(string path)
{
var fileName = GetFileNameFromPath(path);

try
{
return File.ReadAllText(path);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"api.Helpers.tryReadFile | {fileName} | DirectoryNotFoundException. Returning empty string.");
return "";
}
catch (FileNotFoundException)
{
Console.WriteLine($"api.Helpers.tryReadFile | {fileName} | FileNotFoundException. Creating empty file at path ({path}) & returning empty string.");
CreateEmptyFile(path);
return "";
}
catch (IOException)
{
Console.WriteLine($"api.Helpers.tryReadFile | {fileName} | IOException. Race condition. Most likely this process and the MetaTrader EA both trying to access/use the file simultaneously. Returning empty string.");
return "";
}
}

private static void CreateEmptyFile(string filePath)
{
File.Create(filePath).Dispose();
}

private static string GetFileNameFromPath(string path)
{
try
{
return path.Split("\\").Last();
}
catch (Exception)
{
try
{
return path.Split("/").Last();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
}