我是使用System.IO的新手。向用戶顯示文件無法加載到程序的消息c#
我有一個應用程序從Web抓取Json文件,只抓取部分數據以顯示在Windows應用程序窗體的控件上。 表單允許用戶將數據保存爲新文件並加載文件,只要它包含我在保存文件時添加的「指示器」,該文件告訴程序它已被我的程序保存。
一切正常。
只要不包含該指示器的文件被加載到程序中,它就不會顯示任何內容,這是我希望它執行的操作,但我也希望Messagebox.Show()彈出並讓其用戶知道爲什麼這些值是空的,爲什麼沒有發生。
if(openFile.ShowDialog() == DialogResult.OK)
{
string dataLine = string.Empty;
using (StreamReader read = new StreamReader(File.OpenRead(openFile.FileName)))
{
dataLine = read.ReadToEnd();
string[] beginningOfData = dataLine.Split(',');
string temporary = string.Empty;
foreach (string line in beginningOfData)
{
//Indicator
if(line.Contains("Indicator")
{
temporary = line.substring(9);
//Goes through the rest of the file
//Converts data to control value and adds it
}
else
{
//Where I tried to display the message box
}
}
}
}
這是我已經試過,但它不工作,因爲我想它也
else
{
MessageBox.Show("Can't load data.");
}
它仍然會顯示在MessageBox即使閱讀該指標在那裏,顯示相應控件內的數據。另外,無論何時我試圖關閉MessageBox,它都會再次顯示它。
所以我決定這個代替:
else if(!line.contains("Indicator"))
{
MessageBox.Show("Can't load data.");
break;
}
,並也以此方式:
else
{
if(!line.contains("Indicator"))
{
MessageBox.Show("Can't load data.");
break;
}
}
我也試圖使之更加具體做
if(line.contains("Indicator") == false)
{
//Code here
}
但它會即使該文件是由程序創建的,仍然會顯示它。
休息;確實阻止了消息框再次出現,但我只希望MessageBox顯示它是不正確的文本文件(不包含指示符),並允許我關閉MessageBox以再次嘗試。
你想要的文件包含一條線,你必須取值爲Indicator'還是要跨越從文件中的所有行只是一個單一的'Indicator'價值? – Deadzone
第一個。 當我打開已創建它的顯示,如文本文件: (只是一個例子) 指標,內容:1,數據2:字, – BeginnerCoder
這被認爲是一個有效的文件: 線路1:「SomeText」則會 2號線:「Indicator」 ... – Deadzone