Longest file path in a folder - how to handle exceptions - c#

This function should find the longest file in a path it get as parameter.
It seems to work well the problem is I’m not sure how to handle exceptions.
In case of PathTooLongException I want to set _MaxPath to -2 and exit the function, in case of other exception set it to -1 and exit the function else set it to longest file path.
I'm not sure what is the right way to handle exceptions in that case.
Probably a dumb question but I’m new with C#...
static int _MaxPath = 0;
public static void GetLongestFilePath(string p)
{
try
{
foreach (string d in Directory.GetDirectories(p))
{
foreach (string f in Directory.GetFiles(d))
{
if (f.Length > _MaxPath)
{
_MaxPath = f.Length;
}
}
GetLongestFilePath(d);
}
}
catch (Exception e)
{
if (e is PathTooLongException)
{
_MaxPath = -1;
}
}
finally
{
System.Environment.Exit(-99);
}
}

You can have multiple catch blocks with multiple Exception types:
try
{
// ...
}
catch (PathTooLongException e)
{
_MaxPath = -2;
return;
}
catch (Exception e) //anything else
{
_MaxPath = -1;
// ...
}
finally
{
// ...
}

You can catch the specific exception type in its own block:
static int _MaxPath = 0;
public static void GetLongestFilePath(string p)
{
try
{
foreach (string d in Directory.GetDirectories(p))
{
foreach (string f in Directory.GetFiles(d))
{
if (f.Length > _MaxPath)
{
_MaxPath = f.Length;
}
}
GetLongestFilePath(d);
}
}
catch (PathTooLongException e)
{
_MaxPath = -2;
}
catch (Exception e)
{
_MaxPath = -1;
}
finally
{
System.Environment.Exit(-99);
}
}

Related

Rethrow exception in for loop

I want to create a method to retry some code with wait when exception occur. How can I get rid of that last exception?
public static T TryWithWait<T>(Func<T> func, int tries, TimeSpan exceptionSleep)
{
if (tries < 1)
throw new Exception("Tries amount cannot be < 1");
for (int i = 0; i < tries; i++)
{
try
{
return func.Invoke();
}
catch
{
if (i == (tries - 1))
throw;
else
Thread.Sleep(exceptionSleep);
}
}
throw new Exception("Code wouldn't compile without that");
}
You can use recursivity !
public static T TryWithWait<T>(Func<T> func, int tries, TimeSpan exceptionSleep, Exception innerException = null)
{
// You must to knows what exception was generated, I put it as InnerException
if (tries < 1) throw new Exception("Tries amount cannot be < 1", innerException);
try
{
return func.Invoke();
}
catch(Exception exception)
{
return TryWithWait(func, --tries, exceptionSleep, exception);
}
}

Process.GetProcessesByName Doesn't work on exe

if (!Main.isAttached)
{
num++;
if (num <= 15)
{
try
{
Main.gameProcess = Process.GetProcessesByName("csgo")[0];
if ((Main.gameProcess == null || !Main.IsModuleLoaded(Main.gameProcess, "client_panorama.dll") ? true : !Main.IsModuleLoaded(Main.gameProcess, "engine.dll")))
{
continue;
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
continue;
}
while (true)
{
if ((Main.clientPanoramaDll == null ? false : Main.engineDll != null))
{
break;
}
Thread.Sleep(100);
Main.clientPanoramaDll = Main.GetModuleHandle(Main.gameProcess, "client_panorama.dll");
Main.engineDll = Main.GetModuleHandle(Main.gameProcess, "engine.dll");
}
Main.isAttached = true;
}
else
{
MessageBox.Show("CSGO Not Open!", "Open the game first.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
base.Close();
break;
}
}
I am trying to program a mod for CSGO but it says it cannot detect the game is opened when it is already opened! I tried changing It to csgo.exe, csgo.exe32, but nothing works. Any tips please?
You didn't share with us your IsModuleLoaded() function so we can't answer this question, but here is the code I use which should solve your problem:
public static IntPtr GetModuleBaseAddress(Process proc, string modName)
{
IntPtr addr = IntPtr.Zero;
foreach (ProcessModule m in proc.Modules)
{
if (m.ModuleName == modName)
{
addr = m.BaseAddress;
break;
}
}
return addr;
}
Process proc = Process.GetProcessesByName("csgo")[0];
var modBase = ghapi.GetModuleBaseAddress(proc, "client.dll");
You can check the return value of GetModuleBaseAddress, if it's equal to IntPtr.Zero then the module was not loaded. It also will serve as the module handle, so you don't need additional redundant code.

List.Add() re-adding previous values

Background:
I'm working on a Console Application that for each line is saved to the specified days log file (for instance January 5, 2017 is 01_05_2017_log_.txt)
Each log gets added as its supposed to, but the problem I can't seem to figure out is why it's adding all the previous values of the List containing the log values again.
So when CurrentLogs.Add("Some log here") is being called it adds Some log here to the CurrentLogs List.
Let's call it again, but this time the string used is another log here. The items in the List are as follows:
Some log here
Some log here
another log here
And then those 3 are re-added if I try to use the .Add method again
I've looked and looked at ways around this, bing, google, no avail.
// This is the List object I'm using.
public class LoggerList<T> : List<T>
{
public event EventHandler OnAdd;
public new void Add(T item)
{
OnAdd?.Invoke(this, null);
base.Add(item);
}
}
Now here is the Logger class where Logger.CurrentLogs.Add() is called f rom
public class Logger
{
// Directory in which logs are stored
private static string _loggerPath = "Logs/";
// Used to check if the Old Logs have already been added to the OldLogs Object
private static bool _alreadyPulled = false;
// Previously saved logs before the current use of the console app
private static readonly List<string> OldLogs = new List<string>();
// Current logs to be added here
public static LoggerList<string> CurrentLogs = new LoggerList<string>();
//EventHandler to Save Logs on add
public static void OnAdd(object sender, EventArgs e)
{
SaveLog();
}
/// <summary>
/// Saves the logs
/// </summary>
public static void SaveLog()
{
if (!Directory.Exists(_loggerPath))
{
Directory.CreateDirectory(_loggerPath);
}
string fileName = _loggerPath + DateTime.Now.ToString("MM_dd_yyyy") + "_log_.txt";
// If the File Exists, contiue with loading
if (File.Exists(fileName))
{
// If the OldLogs have not already been pulled, pull them
if (!_alreadyPulled)
{
var oldLogs = File.ReadAllLines(fileName).ToList();
foreach (var i in oldLogs)
{
OldLogs.Add(i);
}
_alreadyPulled = true; // Let know that the OldLogs have already been pulled this instance
}
List<string> lines = OldLogs;
lines.AddRange(CurrentLogs);
File.Delete(fileName);
var sr = File.CreateText(fileName);
foreach (string x in lines)
{
sr.WriteLine(x);
}
sr.Flush();
sr.Close();
}
// Only go here if the file doesn't exist
else
{
var sr = File.CreateText(fileName);
foreach (string x in CurrentLogs)
{
sr.WriteLine(x);
}
sr.Flush();
sr.Close();
}
}
}
Here is Program.cs (Adding this as this is where the Messenger class is called
class Program
{
static void Main(string[] args)
{
Logger.CurrentLogs.OnAdd += Logger.OnAdd;
CommandManager.InitCommands();
CheckForEntries();
}
private static void CheckForEntries()
{
while (true)
{
Console.ForegroundColor = ConsoleColor.White;
var text = Console.ReadLine();
try
{
if (!SendEntry(text))
{
Console.WriteLine("Failed to send");
}
}
catch (CommandNotFoundException ex)
{
Messenger.Send("Commmand does not exist (" + text.GetWords()[0] + ")");
}
}
}
private static bool SendEntry(string text)
{
try
{
if (text.FirstCharacter() != "/")
{
return false;
}
else
{
string text2 = text.Substring(1);
string commandname = text2.GetWords()[0];
foreach (Command c in CommandManager.RegisteredCommands)
{
if (c.Name.ToLower() == commandname.ToLower())
{
c.Run(text2.Substring(commandname.Length));
return true;
}
else
{
foreach (string alias in c.Aliases)
{
if (alias.ToLower() == commandname.ToLower())
{
c.Run(text2.Substring(commandname.Length + 1));
return true;
}
}
}
}
throw new CommandNotFoundException();
}
}
catch (CommandNotFoundException ex)
{
throw ex; // Placed here so that the catch (Exception) does not go beyond
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
}
And here is Messenger.cs (Where the .Add directly happens)
// Color codes
private static readonly string[] codes =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f"
};
private static string Format(string rawText)
{
return "&e" + TimeStamp() + " " + rawText;
}
public static string TimeStamp()
{
return "<" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") + ">";
}
public static void Send(string textRaw)
{
Logger.CurrentLogs.Add(Format(textRaw).Substring(2));
string text = Format(textRaw);
List<int> skipOver = new List<int>();
for (int txt = 0; txt <= text.Length - 1; txt++)
{
char[] chars = text.ToCharArray();
if (chars[txt].ToString() == "&")
{
List<string> hi = codes.ToList();
if (hi.Contains(chars[txt + 1].ToString().ToLower()))
{
skipOver.Add(txt);
skipOver.Add(txt + 1);
}
}
}
for (int x = 0; x <= text.Length - 1; x++)
{
char[] chars = text.ToCharArray();
if (chars[x] == "&".ToCharArray()[0]) continue;
if (x <= 1 || skipOver.Contains(x)) continue;
char behind2 = chars[x - 2];
char behind1 = chars[x - 1];
if (behind2.ToString() == "&")
{
bool isGoodCode = false;
foreach (string s in codes)
{
if (s.ToLower() == behind1.ToString().ToLower())
{
isGoodCode = true;
}
}
if (isGoodCode)
{
skipOver.Add(x - 2);
skipOver.Add(x - 1);
if (x < text.Length - 1)
{
Color baseColor = ToColor(behind1.ToString());
ConsoleColor cColor = ToConsoleColor(baseColor);
Console.ForegroundColor = cColor;
Console.Write(chars[x]);
}
else if (x == text.Length - 1)
{
Color baseColor = ToColor(behind1.ToString());
ConsoleColor cColor = ToConsoleColor(baseColor);
Console.ForegroundColor = cColor;
Console.WriteLine(chars[x]);
}
}
else
{
if (x < text.Length - 1)
{
Console.Write(chars[x - 2]);
Console.Write(chars[x - 1]);
Console.Write(chars[x]);
}
else if (x == text.Length - 1)
{
Console.Write(chars[x - 2]);
Console.Write(chars[x - 1]);
Console.WriteLine(chars[x]);
}
}
}
else
{
if (x < text.Length - 1)
{
Console.Write(chars[x]);
}
else if (x == text.Length - 1)
{
Console.WriteLine(chars[x]);
}
}
}
}
In these lines
List<string> lines = OldLogs;
lines.AddRange(CurrentLogs);
"lines" points to the same object as "OldLogs". Therefore you keep adding entries to the same list.
You could try copying instead:
var lines = new List<string>(OldLogs);

Problems with the exceptions of the substitution derivative method

I'm trying to understand System.Exception class and I got some problems with override function. I try to intercept exception of DivideByZero and Write my user message which I generate in function of derivative class from System.Exception. this is my code:
public class zeroDivision
{
public void Deleter()
{
double z; int i = 0;
try
{
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (zeroMessage e) **<====problem here: DivideByZeroException**
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, e.Message);
}
}
}
public class zeroMessage : System.Exception <--here debugger even doesn't come
{
public override string Message
{
get
{
string msg = base.Message;
msg = "Деление на ноль ЗАПРЕЩЕНО!!!";
return msg;
}
}
}
class Program
{
static void Main(string[] args)
{
zeroDivision zero = new zeroDivision();
zero.Deleter();
Console.Read();
}
}
When I call: catch(zeroMessage e) - it unhandled, but if I call: catch(Exception e) - it works. Where is my fault? I don't understand
-------------------------------
After some help of forum's masters, I remade this task with working functions. Maybe it will be useful for anybody:
public class zeroDivision
{
public void Deleter() //First way
{
double z; int i = 0;
try
{
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (DivideByZeroException)
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, "Делить на ноль НИЗЗЯ!!!");
}
}
public double Deleter2(int a, int b) //Second way
{
if (b == 0) throw new zeroMessage();
return a / b;
}
public void prn(int i, int j) //Third way
{
try
{
Console.WriteLine(Deleter2(i, j));
}
catch (zeroMessage z)
{
Console.WriteLine(z.Message);
}
}
public void firstDeleter() //Updated Yesterday's code - Forth way
{
double z; int i = 0;
try
{
if (i == 0) throw new zeroMessage(); //!!!
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (zeroMessage e)
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, e.Message);
}
}
}
public class zeroMessage : System.Exception
{
public override string Message
{
get
{
string msg = base.Message;
msg = "Деление на ноль ЗАПРЕЩЕНО!!!";
return msg;
}
}
}
class Program
{
static void Main(string[] args)
{
zeroDivision zero = new zeroDivision();
zero.Deleter();
try
{
double result = zero.Deleter2(10, 0);
Console.WriteLine(result);
}
catch (zeroMessage z)
{
Console.WriteLine(z.Message);
}
zeroDivision zero1 = new zeroDivision();
zero1.prn(10, 0);
zeroDivision zero2 = new zeroDivision();
zero2.firstDeleter();
Console.Read();
}
}
When you are trying to divide CLR throws the exception of type DivideByZeroException.
There is no way for CLR to know that you want to throw other exception.
But if you want to play with your new exception, you can do it like this:
public double Divide(int a, int b)
{
if(b == 0) throw new zeroMessage();
return a /b;
}
and use it:
try
{
var result = Divide(10, 0);
}catch(zeroMessage exc)
{
//here you will catch your exception.
}
However there is no sense in such exception, except education goals.
Judging by your code alone, nowhere do you actually throw zeroMessage.
If you want to intercept DivideByZeroException then that is what you have to do.
Get rid of the zeroMessage type, since it has no bearing on the results here, and change the catch code to this:
catch (DivideByZeroException e)
{
...
Note that the code in the runtime will throw exceptions known to the runtime at the time the runtime was compiled. It will not magically pick up that you want to substitute some exceptions for your own. The only way to catch a "x / 0" problem in your code is to catch the DivideByZeroException, not by inventing your own exception type.
Both DivideByZeroException and your zeroMessage class derive from System.Exception. However that doesn´t mean that DivideByZeroException derives from zeroMessage!
What are you trying to achieve? Use System.Exception if you want to catch all possible exceptions, and use DivideByZeroException and the likes, when you are interested in a particular exception like:
double z; int i = 0;
try
{
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (DivideByZeroException e)
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, e.Message);
}
catch(Exception e)
{
Console.WriteLine("Unexpected error: ", e.Message);
}

StackOverflow Exception at GraphicsCreator().FillEllipse

Im getting a stackoverflow exception when i'm filling the ellipse not just one ellipse but many ellipses.
I dont think it is a problem from the graphics creator. But i can't figure out why the debugger is pointing a stackoverflow exception at the FillEllipse command
public void createPath(Stance currentStance)
{
if(toSort.Count > 0)
{
toSort.Remove(currentStance);
counter++;
}
this.currentForm.FillEllipse(new SolidBrush(Color.Red),new Rectangle(currentStance.location.X-3, currentStance.location.Y - 3, 6 , 6));
foreach(Stance subStance in currentStance.childStances)
{
double weight = level(currentStance, subStance, 1)+ currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
subStance.StanceWeight = weight;
toSort.Add(subStance);
}
else
{
if(weight > subStance.StanceWeight)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
}
catch (NullReferenceException e)
{
Console.WriteLine("null reference");
}
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
subStance.StanceWeight = weight;
}
}
}
foreach(Stance subStance in currentStance.secondChildStances)
{
double weight = level(currentStance, subStance, 1) + currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
toSort.Add(subStance);
subStance.StanceWeight = weight;
}
else
{
if (weight > subStance.StanceWeight)
{
if(subStance.parentStance != null)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
}
catch(NullReferenceException e)
{
Console.WriteLine("null reference");
}
}
}
}
}
toSort.Sort(new Stance());
if(toSort.Count != 0)
{
createPath((Stance)toSort[0]);
}
}
it is a recursive method but it cant recurse to infinity as it always pops a single object from the toSort ArrayList
That's because it is in the attempt to make the call to FillEllipse that the stack actually runs out.
Of course the stack overflow has to be caused by a flaw in your logic that causes your createPath method to be called recursively either (probably) indefinitely or too deeply for the stack to accommodate all the needed activation frames.
Use a while loop instead of recursion to avoid loading up the stack.
Here is your code modified that might work:
public void createPath(Stance stance)
{
var currentStance = stance;
while(toSort.Count >0)
{
toSort.Remove(currentStance);
counter++;
this.currentForm.FillEllipse(new SolidBrush(Color.Red),new Rectangle(currentStance.location.X-3, currentStance.location.Y - 3, 6 , 6));
foreach(Stance subStance in currentStance.childStances)
{
double weight = level(currentStance, subStance, 1)+ currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
subStance.StanceWeight = weight;
toSort.Add(subStance);
}
else
{
if(weight > subStance.StanceWeight)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
}
catch (NullReferenceException e)
{
Console.WriteLine("null reference");
}
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
subStance.StanceWeight = weight;
}
}
}
foreach(Stance subStance in currentStance.secondChildStances)
{
double weight = level(currentStance, subStance, 1) + currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
toSort.Add(subStance);
subStance.StanceWeight = weight;
}
else
{
if (weight > subStance.StanceWeight)
{
if(subStance.parentStance != null)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
}
catch(NullReferenceException e)
{
Console.WriteLine("null reference");
}
}
}
}
}
toSort.Sort(new Stance());
currentStance = (Stance)toSort[0];
}
}

Categories

Resources