文件另存为、打开文件、打开目录、提示框

文件另存为

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 = fileName,
};
if (dlg.ShowDialog() == Forms.DialogResult.OK)
{
    string filePath = dlg.FileName;
    File.WriteAllBytes(filePath, data);
}            

打开文件

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
}

路径字符串解析

// 根目录
var rootDir = Path.GetPathRoot(filePath);
// 获取目录
var dir = Path.GetDirectoryName(filePath);
// 文件名称 有后缀
var name = Path.GetFileName(filePath);
// 文件名称 没有后缀
var name = Path.GetFileNameWithoutExtension(filePath);
// 后缀扩展名称
var suffer = Path.GetExtension(filePath);
posted @ 2019-12-31 18:24  wesson2019  阅读(251)  评论(0编辑  收藏  举报