我有下面的应用程序。为了让读者更容易测试,我稍作修改。我注意到,当我使用扩展名设置文件名时,例如test.txt,txt扩展名被对话框删除。不过,我希望用户能够指定扩展名,更重要的是我希望能够设置扩展名。在我看来,破解它的一种方法是根据我的扩展名修改过滤器。这是唯一的方法吗?SaveFileDialog从设置文件名中删除扩展名
我正在使用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();
}
}
}
我复制了您的代码,并且仅更改了消息框中对“表单”的引用。这对我来说可以。我总是得到我输入对话框的确切文件。 – DonBoitnott
不是我认为它引起任何问题,但是无论如何,“form”对象的目的是什么?它是空的,什么都不做。你不需要固定你所知道的MessageBox。 – DonBoitnott
在我的系统上,我发现该对话框遵循用户在操作系统级别设置的任何内容。如果扩展名在文件浏览器中隐藏,那么它们也会隐藏在对话框中,而相反的情况也是如此。 –