文件操作笔记

//打开文件夹
using (OpenFileDialog ofd = new OpenFileDialog())
{
                ofd.Filter = "jpg|*.jpg|png|*.png";
                ofd.RestoreDirectory = true;
                ofd.FilterIndex = 1;
                if (ofd.ShowDialog() == DialogResult.Cancel) return;
                string path = ofd.FileName;
                //
}
//保存文件路径
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "jpg|*.jpg|png|*.png";
                sfd.RestoreDirectory = true;
                sfd.FilterIndex = 1;
                if (sfd.ShowDialog() == DialogResult.Cancel) return;
                string path = sfd.FileName;
                //....
            }
//文件夹是否存在,文件是否存在
 if (!Directory.Exists(file))
{
     Directory.CreateDirectory(file);
}
//文件是否存在
File.Exists(it.path)
File.Create(it.path);
File.Delete(desDir + @"\" + fileName);
File.Move(oldpath, desDir + @"\" + fileName);
 /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="path">地址</param>
        /// <param name="data">数据</param>
        public void WriteTxt(string path, List<string> data)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(string.Join("\r\n", data));
                //清空缓冲区
                sw.Flush();
                sw.Close();
            }
        }
/// <summary>
        /// 获得指定路径下所有文件名
        /// </summary>
        public void GetFileName(List<fileNameData> fnd, string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (FileInfo fi in root.GetFiles())
            {
                var fullFileName = Path.GetFileNameWithoutExtension(fi.FullName);//完整文件名
                var fileName = fullFileName.Split('-').FirstOrDefault().Trim();
                fnd.Add(new fileNameData()
                {
                    path = fi.FullName,
                    fullFileName = fullFileName,
                    fileName = fileName,
                    suffix = Path.GetExtension(fi.FullName)
                });
            }
        }

猜你喜欢

转载自www.cnblogs.com/shuaimeng/p/10333235.html