【问题标题】:Static string using File.ReadAllText使用 File.ReadAllText 的静态字符串
【发布时间】:2013-07-16 00:05:23
【问题描述】:

我正在尝试将File.ReadAllText 用作静态只读 字符串。我的问题是我正在用 .NETz 编译它,当我的程序启动时它会查找我的字符串,如果不是 发现我遇到了一个令人讨厌的异常。是否可以通过某种方式使用 if/else 来解决这个问题?

通常我会让它弹出一个消息框或在标签中说明找不到文件。如果找不到文件,则使用 .Netz 会收到错误消息并且程序无法启动。

这是我在整个程序中使用的静态字符串

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

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

【问题讨论】:

标签: c# .net windows .net-3.5


【解决方案1】:

与其在声明中内联,不如将工作移至静态构造函数。然后添加 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?
        }
    }
}

请注意many reasons 除了在路径中找不到之外,为什么读取文件可能会失败。您可能还想考虑捕捉其中的一些。

【讨论】:

  • 或者在FileNotFoundException的情况下,使用File.Exists检查文件是否确实存在。
  • 我知道该文件不存在。问题在于它是如何处理的。
  • @user1908061:检查文件是否存在不会阻止它在您打开它之前被另一个线程删除。见blog.mischel.com/2013/06/27/file-exists-is-only-a-snapshot
  • @chrissinclair,我对它的归属感到困惑。我已经编辑了主要问题并添加了我所拥有的。
  • @user2190928:现在在您的表单中很好。虽然我更愿意将其移至某种专用的 Config 类,而不是将其嵌入到您的 Form1 对象中。
【解决方案2】:
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;

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多