系统特殊目录路径
//取得特殊文件夹的绝对路径
//桌面
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//收藏夹
Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
//我的文档
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//最近使用的文档
Environment.GetFolderPath(Environment.SpecialFolder.Recent);
文件操作
![]()
void CheckFileExists()
{
//通过函数File.Exists方法判断文件是否存在
//string fileName = @"C:\Dell\demo.txt";
//if (File.Exists(fileName))
//{
// Console.WriteLine("File {0} exists.", fileName);
//}
string fileName = @"C:\Dell\demo.txt";
if (File.Exists(fileName))
this.tbInfo.AppendText(fileName + "存在\r\n"); else
this.tbInfo.AppendText(fileName + "不存在\r\n");
}
void GetFileInfo()
{
//通过FileInfo取得文件属性
string fileName = this.tbFile.Text;
FileInfo info = new FileInfo(fileName);
// 判断文件是否存在
this.tbInfo.AppendText("文件是否存在:" + info.Exists.ToString() + "\r\n");
// 获取文件名
this.tbInfo.AppendText("文件名:" + info.Name + "\r\n");
// 获取文件扩展名
this.tbInfo.AppendText("扩展名:" + info.Extension + "\r\n");
// 获取文件躲在文件夹
this.tbInfo.AppendText("所在文件夹:" + info.Directory.Name + "\r\n");
// 获取文件长度
this.tbInfo.AppendText("文件长度:" + info.Length + "\r\n");
// 获取或设置文件是否只读
this.tbInfo.AppendText("是否只读:" + info.IsReadOnly + "\r\n");
// 获取或设置文件创建时间
this.tbInfo.AppendText("创建时间:" + info.CreationTime + "\r\n");
// 获取或设置文件最后一次访问时间
this.tbInfo.AppendText("最后一次访问时间:" + info.LastAccessTime + "\r\n");
// 获取或设置文件最后一次写入时间
this.tbInfo.AppendText("最后一次写入时间:" + info.LastWriteTime + "\r\n");
}
void CopyFile()
{
// 复制文件
// 原文件
string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
// 新文件
string destFileName = @"e:\timer.png";
File.Copy(sourceFileName, destFileName);
}
void MoveFile()
{
// 移动文件,可以跨卷标移动
// 文件移动后原文件被删除
string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
string destFileName = @"e:\timer.png";
File.Move(sourceFileName, destFileName);
}
void DeleteFile()
{
//删除指定文件
string fileName = @"C:\Dell\demo.txt";
// 删除前需检查文件是否存在
if (File.Exists(fileName))
File.Delete(fileName);
}
void PickFile()
{
//从工具箱拖入OpenFileDialog控件命名为ofd,或者直接定义
OpenFileDialog ofd = new OpenFileDialog();
// 当所选文件不存在时给出警告提示
ofd.CheckFileExists = true;
// 是否添加默认文件扩展名
ofd.AddExtension = true;
// 设置默认扩展文件名
ofd.DefaultExt = ".txt";
// 设置文件类型筛选规则,
// 组与组之间用“|”分隔,每组中文件类型与扩展名用“|”分割,多个文件类型用“;”分隔
ofd.Filter = "文本文件|*.txt|图片文件|*.png;*gif;*.jpg;*.jpeg;*.bmp";
// 设置是否支持多选
ofd.Multiselect = true;
// 设置对话框标题
ofd.Title = "选择文件:";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.tbFile.Text = ofd.FileName;
// 依次列出多选的文件名称
foreach (string fname in ofd.FileNames)
{
this.tbInfo.AppendText(fname + "\r\n");
}
}
}
void RenameFile()
{
// 使用VB方法,重命名文件
Computer myPC = new Computer();
string sourceFileName = @"C:\Users\Dai\Desktop\截图\timer.png";
string newFileName = @"timer12.png";
//必须是名称,而不是绝对路径
myPC.FileSystem.RenameFile(sourceFileName, newFileName);
myPC = null;
}
View Code