静态string使用File.ReadAllText

我正在尝试使用File.ReadAllText作为静态只读string。 我的问题是我正在与.NETz编译它,当我的程序启动时,它会查找我的string,如果没有find我得到一个讨厌的exception。 是否有可能通过使用if / else来解决这个问题?

通常我会popup一个消息框或标签说明文件没有find。使用.Netz如果没有find文件,我得到一个错误消息,程序无法启动。

这是我的程序中使用的静态string

 static readonly string config = File.ReadAllText("config.ini"); 

我使用.Netz来包含我的dll。

而不是与声明内联,将工作移到静态构造函数。 然后添加try/catch块来处理错误情况就变得微不足道了:

 public class MyClass { static readonly string config; static MyClass() { try { config = File.ReadAllText("config.ini"); } catch (FileNotFoundException) { //do something else //use a default configuration? //report to the user? //crash and burn? } } } 

请注意,读取文件的原因有很多,除了在路径中找不到的地方。 你也可以考虑去捕捉其中的一些。

 public partial class Form1 : Form { public class configi { public static string config; static configi() { try { config = File.ReadAllText("config.ini"); } catch (FileNotFoundException e) { Console.WriteLine(e.Message); return; } } } public Form1() { InitializeComponent(); } static string username = (Environment.GetEnvironmentVariable("USERNAME")); static string Backups = configi.config + @"\" + username + @"\" + "Backups" + @"\"; static string items;