gpt4 book ai didi

c# - 类中的 StreamReader 为空

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:57 25 4
gpt4 key购买 nike

我有这个在类中创建 SqlConnection 字符串的方法。我从 .txt 文件中读取了数据,但问题是如果没有插入数据,应用程序甚至不会打开。我想知道如何在消息框中抛出异常并将该命令直接插入此类方法中。我不确定这是否可能。抱歉,如果我的回答过于琐碎或毫无意义。我很长时间没有编程了。

internal static class DataSource
{
private static string _ConnectionString;
public static string ConnectionString
{
get
{
if (_ConnectionString == null)
_ConnectionString = FunctionToDynamicallyCreateConnectionstring();
return _ConnectionString;
}
}
private static string FunctionToDynamicallyCreateConnectionstring()
{

string path = "C:\\Users\\marek\\Documents\\Visual Studio 2012\\Projects\\tours\\tours\\sql_string.txt";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));

SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();

cb.DataSource = sr.ReadLine();
cb.InitialCatalog = sr.ReadLine();
cb.UserID = sr.ReadLine();
cb.Password = sr.ReadLine();
return cb.ToString();

}

最佳答案

当您的应用通过 try/catch 启动时,包装对 DataSource.ConnectionString 的访问。下面是一些伪代码:

public void OnAppStart()
{
string connString = null;
try
{
connString = DataSource.ConnectionString;
}
catch (IOException ioe)
{
MessageBox.Show("Hey, the file doesn't exist!");
}
catch (ArgumentNullException ane)
{
MessageBox.Show("Hey, the file is missing information!");
}
//You should be prepared to deal with a null or malformed connString
//from this point forwards
}

关于c# - 类中的 StreamReader 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com