文件另存为、打开文件、打开目录、提示框
文件另存为
using Forms = System.Windows.Forms;
string fileName = $"aaa_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xls";
Forms.SaveFileDialog dlg = new Forms.SaveFileDialog()
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Filter = "工作表|*.xls;*.xlsx",
FileName = RemoveInvalidFileNameChars(fileName),
};
if (dlg.ShowDialog() == Forms.DialogResult.OK)
{
string filePath = dlg.FileName;
File.WriteAllBytes(filePath, data);
}
其中,data是数组,若源数据是stream流,就需要stream转换成byte[];
若流是只读的,比如ReadOnlyStream,可以转换成文件流,直接写入指定文件内。
打开文件
var dlg = new System.Windows.Forms.OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Filter = "图像文件|*.jpg;*.png;*.jpeg;*.bmp;*.gif|所有文件|*.*"
};
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var fileName = dlg.FileName;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var frame = BitmapFrame.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
var width = frame.PixelWidth;
var height = frame.PixelHeight;
if (width != 1920 || height != 1080)
{
// 图大小必须是1920*1080
return;
}
}
// do sth
}
打开目录
var dlg = new System.Windows.Forms.FolderBrowserDialog
{
Description = "请选择一个目录",
SelectedPath = "D:",
//RootFolder = _filePath,
};
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (!string.IsNullOrEmpty(dlg.SelectedPath))
{
var fileDir = dlg.SelectedPath;
// do sth
}
}
提示框
var dlg = MessageBox.Show(this, "提示?", "标题", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk);
if (dlg == MessageBoxResult.OK)
{
// do sth
}