-1

I am using discord auto joiner, and when the discord is not found in the pc. It shows an exception result in breaking the whole UI and messing stuff up.

Now in order to do that I tried using catch exception but it won't work for public static string, it only work for public static void. Then I tried if file exists. Same thing with that.

This is my code....
  public static string GetToken(string path, bool isLog = false)
      {
          if (File.Exists(path))
          {
              byte[] bytes = File.ReadAllBytes(path);
              string @string = Encoding.UTF8.GetString(bytes);
              string text = "";
              string text2 = @string;
              while (text2.Contains("oken"))
              {
                  string[] array = Sub(text2).Split(new char[]
                  {
                  '"'
                  });
                  text = array[0];
                  text2 = string.Join("\"", array);
                  if (isLog && text.Length == 59)
                  {
                      break;
                  }
              }
              return text;

          }
      }

I just want to remove the exception.

  • 1
    Your question is not clear. What exception you are getting ? File.Exists should work in normal scenario – Praveen M Jul 16 '19 at 22:34
  • @PraveenM With this code I am using, it says "Not all code returns a value". – ThunderModsYT Jul 16 '19 at 22:37
  • 3
    Imagine that you run your program and the file doesn't exists: what should the function `GetToken` return? – Josh Part Jul 16 '19 at 22:40
  • You have a `return` statement inside your `if` block, but if that block doesn't execute, then you need to return something outside the `if` block. – Rufus L Jul 16 '19 at 22:49
  • Then its not exception . Its compilation error . Return string.empty or useful string as per your need after closing If – Praveen M Jul 16 '19 at 22:56
  • @JoshPart if someone run programs and the file is not found I simply just want the program to show an error that the file is not found and continue with the code. – ThunderModsYT Jul 16 '19 at 23:13
  • @ThunderModsYT try looking up the difference between public static string and public static void. In one case you are specifying that the function will return a string, in the other you are specifying that the function returns nothing – Eitan Seri-Levi Jul 16 '19 at 23:14

1 Answers1

0

As Josh already pointed out, the error 'Not all code paths return a value...' you're receiving is because the method doesn't handle the case when File.Exists(path) returns false. See the below:

public static string GetToken(string path, bool isLog = false)
{
    if (File.Exists(path))
    {
        string text = string.Empty;
        // set text...
        return text;
    }
    else
    {
        return string.Empty // <-- or return something more meaningful
    }
}
bvanfleet
  • 19
  • 4