我有下面的应用程序。为了方便读者在这里测试,我稍微修改了一下。我注意到,当我使用扩展名设置文件名时,例如 test.txt,对话框会删除 txt 扩展名。但是我希望用户能够指定扩展名,更重要的是我希望能够设置扩展名。我认为破解它的一种方法是根据我拥有的扩展名修改过滤器。这是唯一的方法吗?
我正在使用 VS 2010 Express。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using System.Windows;
namespace SpeedDating
{
partial class Program
{
[STAThread]
static void Main(string[] args)
{
Form form = new Form();
form.WindowState = FormWindowState.Minimized;
form.ShowInTaskbar = false;
form.TopMost = true;
form.Show();
string filename = "test.txt";
string ext = filename.Substring(filename.LastIndexOf('.'));
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.SupportMultiDottedExtensions = true;
dialog.AddExtension = false;
dialog.Filter = "All files (*.*)|*.*";
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
MessageBox.Show(form, "Copied file.");
}
catch (NotSupportedException ex)
{
MessageBox.Show(form, "Probably removed the original file.");
}
}
else if (result != DialogResult.Cancel)
{
MessageBox.Show(form, "No path found to write to.");
}
form.Close();
}
}
}