2

拡張子が .txt のファイルを開くにはどうすればよいですか。ファイルが .txt ファイルでない場合、プログラムにエラー メッセージを表示させたいです。以下のコードを変更できるコードが必要です。

private void button1_Click(object sender, EventArgs e)
{
   OpenFileDialog of = new OpenFileDialog();
   of.ShowDialog();
   textBox1.Text = of.FileName;
}

このループを入れたいとしましょう。

if fileextension is .txt then 
OpenFileDialog of = new OpenFileDialog();
            of.ShowDialog();
            textBox1.Text = of.FileName;
else show error message(like can not open this file)
4

3 に答える 3

8

私が正しく理解したように、ダイアログに txt ファイルのみを表示したいですか? その場合は、 Filterプロパティを使用します。

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Text files (*.txt)|*.txt";
于 2012-04-21T08:46:39.477 に答える
1

これにはPath.GetExtensionメソッドを使用できます

OpenFileDialog of = new OpenFileDialog();
if(of.ShowDialog() == DialogResult.OK)
{
    if(Path.GetExtension(of.FileName).Equals("txt",
                             StringComparison.InvariantCultureIgnoreCase))
                                textBox1.Text = of.FileName;
}
于 2012-04-21T08:42:59.970 に答える
0

txt 拡張子のみを許可する場合は、すべての拡張子を許可しないでください。

of.Filter = "Text Files|*.txt";

OpenFileDialog が txt 拡張ファイルのみを受け入れるようにします。

于 2012-04-21T08:50:44.293 に答える