これはおそらく簡単な質問です。私は VS 2012 で WinForms C# アプリケーションを作成しています。ユーザーが C:\Users\Desktop\filename に書き込んだが、パスの .csv 部分を省略したとします。実行ボタンをクリックした後に .csv を追加する方法はありますか?
どんな助けでも大歓迎です。
使用できますPath.ChangeExtension
。
// Nota bene: Path.ChangeExtension does not change textBox1.Text directly (or any
// argument given), you MUST use the result if you care about it.
string newPath = Path.ChangeExtension(textBox1.Text, "csv");
ピリオドはオプションであり、ファイル名コンポーネントに拡張子を含める必要はありません。
将来の参考として、ファイルまたはディレクトリへのパスで行う必要がある何かSystem.IO.Path
を考えることができれば.. そのクラスで一般的なタスクがサポートされていないことはまれです。
文字列内の有効な拡張子を変更したくない場合は、代わりに次のようにすることができます。
// first test for an extension
if(!Path.HasExtension(textBox1.Text.Trim()))
{
// then add on '.csv' if one does not exist
string path = Path.ChangeExtension(textBox1.Text.Trim(), ".csv");
// ... use path ...
}