我有以下应用程序。我稍微修改了它,以方便读者在这里测试。我注意到当我使用扩展名设置文件名时,例如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();
}
}
}
答案 0 :(得分:3)
更重要的是我希望能够设置扩展名
您可以设置 .DefaultExt(), .AddExtension(), .Filter()和 .FilterIndex( )属性:
string filename = "test.xyz";
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.SupportMultiDottedExtensions = true;
dialog.Filter = "All files (*.*)|*.*";
dialog.DefaultExt = System.IO.Path.GetExtension(filename);
if (dialog.DefaultExt.Length > 0)
{
dialog.AddExtension = true;
dialog.Filter = dialog.DefaultExt + " files (*." + dialog.DefaultExt + ")|*." + dialog.DefaultExt + "|" + dialog.Filter;
dialog.FilterIndex = 0;
}
dialog.FileName = DateTime.Now.ToString("yyyyMMdd");
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
Console.WriteLine(dialog.FileName);
}
*请注意,如果在文件资源管理器中关闭显示“文件扩展名”的选项,则对话框也会隐藏扩展名... 但是以上设置会将设置的扩展名添加到对话框返回的.FileName()值。