您的位置:首页 > 编程语言 > C#

笔记: C#文件操作方法学习

2018-02-01 15:16 190 查看
学习笔记:文件目录创建、文件拷贝、文件删除、文件移动、文件夹移动、文件夹删除、获取文件信息

获取app所在资源根路径:

public static string get_app_path()
{

string app_name = Process.GetCurrentProcess().MainModule.FileName;

string path = Path.GetDirectoryName(app_name);

return path;

}

创建文件目录:

public void create_dir(string path)

{

DirectoryInfo folder = new DirectoryInfo(path);

if (!folder.Exists)

Directory.CreateDirectory(path);

}

文件拷贝:

public void copy_file(string path)

{

string[] path_segs = path.Split('\\');

string name = path_segs[path_segs.Length - 1];

string save_path = Path.Combine(get_app_path(), name);

FileInfo file = new FileInfo(path);

if (file.Exists)

{

file.CopyTo(save_path, true);

}

}

文件删除:

public void delete_file(string path)

{

FileInfo file = new FileInfo(path);

if (file.Exists)

{

file.Delete();

}

}

文件夹删除:

public void delete_folder(string path)

{

DirectoryInfo folder = new DirectoryInfo(path);

if (folder.Exists)

{

folder.Delete(true);

}

}

文件移动:

public void move_file(string file_path, string dst_path)

{

FileInfo file = new FileInfo(file_path);

if (file.Exists)

{

file.MoveTo(dst_path);

}

}

文件夹移动:

public void move_folder(string folder_path, string dst_path)

{

DirectoryInfo folder = new DirectoryInfo(folder_path);

if (folder.Exists)

{

folder.MoveTo(dst_path);

}

}

获取文件的信息:

public FileInfo get_file_info(string path)

{

FileInfo file = new FileInfo(path);

if (!file.Exists)

throw new FileNotFoundException("File not found: " + path);

Console.WriteLine("创建时间:" + file.CreationTime.ToString());

Console.WriteLine("文件大小:" + file.Length.ToString());

return file;

}

打印指定目录下所有文件名称、及所有子文件夹测试:

public void test(path)

{

DirectoryInfo folder = new DirectoryInfo(path);

if (!folder.Exists)

throw new DirectoryNotFoundException("Folder not found: " + path);

foreach (DirectoryInfo sub_folder in folder.GetDirectories())

{

Console.WriteLine(sub_folder.Name);

}

foreach (FileInfo file in folder.GetFiles())

{

Console.WriteLine(file.Name);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: