首页 > 解决方案 > 如果文件存在于公共静态字符串中,我该如何使用?错误:并非所有代码都返回值

问题描述

我正在使用不和谐自动连接器,当在电脑中找不到不和谐时。它显示了一个异常结果,导致整个 UI 被破坏并弄乱了东西。

现在为了做到这一点,我尝试使用 catch 异常,但它不适用于公共静态字符串,它只适用于公共静态 void。然后我尝试了文件是否存在。与此相同。

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;

          }
      }

我只想删除异常。

标签: c#

解决方案


File.Exists(path)正如 Josh 已经指出的那样,您收到的错误“并非所有代码路径都返回值......”是因为该方法在返回 false时无法处理这种情况。见下文:

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
    }
}

推荐阅读