下記コードで変数宣言は外でしていますが、try内の変数を外で操作できません。
switchの終わりまでtryにすると実行できるのですが、宣言場所に問題があるのでしょうか?
using 省略
namespace trycatch
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) { string mt1; string st1; string strTime1; string strTime2; try //StreamReaderだけをtryにすると外でmt1をいじれない { StreamReader sr1 = new StreamReader(@"d:\1sample.txt", Encoding.GetEncoding("Shift_JIS")); mt1 = sr1.ReadToEnd(); sr1.Close(); } catch (Exception ex) { label1.Text = ex.Message; } StreamReader sr2 = new StreamReader(@"d:\2sample.txt", Encoding.GetEncoding("Shift_JIS")); st1 = sr2.ReadToEnd(); sr2.Close(); strTime1 = mt1.Substring(10, 28); //ここでエラー strTime2 = st1.Substring(10, 28); switch (strTime1.CompareTo(strTime2)) { case -1: textBox1.Text = "strTime1はstrTime2より前の日時です"; break; case 0: textBox1.Text = "strTime1はstrTime2は同じ日時です"; break; case 1: textBox1.Text = "strTime1はstrTime2より後の日時です"; break; } } }
}
エラーというのは、コンパイル時のエラーですか?実行時のエラーですか?
また、エラーメッセージは何ですか?
回答4件