目录
[打开一个弹框,选择 文件/文件夹,并获取路径](#打开一个弹框,选择 文件/文件夹,并获取路径)
删除文件和删除文件夹
cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 删除文件和文件夹
{
class Program
{
static void Main(string[] args)
{
string path1 = Environment.CurrentDirectory + "\\MyTest";
string path2 = Environment.CurrentDirectory + "\\新建文本文档.txt";
//删除文件夹
if (Directory.Exists(path1))
Directory.Delete(path1, true);
//删除文件
if (File.Exists(path2))
File.Delete(path2);
Console.ReadKey();
}
}
}
拷贝文件到另一个目录
cs
/// <summary>
/// 拷贝文件到新的目录,如果存在则覆盖
/// </summary>
/// <param name="path1">要拷贝的文件,不能是文件夹</param>
/// <param name="path2">新的路径,可以使用新的文件名,但不能是文件夹</param>
public static void CopyFile(string path1, string path2)
{
//string path1 = @"c:\SoureFile.txt";
//string path2 = @"c:\NewFile.txt";
try
{
FileInfo fi1 = new FileInfo(path1);
FileInfo fi2 = new FileInfo(path2);
//创建路径1文件
//using (FileStream fs = fi1.Create()) { }
if (!File.Exists(path1))
{
Console.WriteLine("要拷贝的文件不存在:" + path1);
return;
}
//路径2文件如果存在,就删除
//if (File.Exists(path2))
//{
// fi2.Delete();
//}
//path2 替换的目标位置
//true 是否替换文件,true为覆盖之前的文件
fi1.CopyTo(path2,true);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
另一种
cs
/// <summary>
/// 拷贝文件到另一个文件夹下
/// </summary>
/// <param name="sourceName">源文件路径</param>
/// <param name="folderPath">目标路径(目标文件夹)</param>
public void CopyToFile(string sourceName, string folderPath)
{
//例子:
//源文件路径
//string sourceName = @"D:\Source\Test.txt";
//目标路径:项目下的NewTest文件夹,(如果没有就创建该文件夹)
//string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewTest");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
//当前文件如果不用新的文件名,那么就用原文件文件名
string fileName = Path.GetFileName(sourceName);
//这里可以给文件换个新名字,如下:
//string fileName = string.Format("{0}.{1}", "newFileText", "txt");
//目标整体路径
string targetPath = Path.Combine(folderPath, fileName);
//Copy到新文件下
FileInfo file = new FileInfo(sourceName);
if (file.Exists)
{
//true 为覆盖已存在的同名文件,false 为不覆盖
file.CopyTo(targetPath, true);
}
}
保存Json文件和读取Json文件
cs
/// <summary>
/// 将序列化的json字符串内容写入Json文件,并且保存
/// </summary>
/// <param name="path">路径</param>
/// <param name="jsonConents">Json内容</param>
private static void WriteJsonFile(string path, string jsonConents)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine(jsonConents);
}
}
}
/// <summary>
/// 获取到本地的Json文件并且解析返回对应的json字符串
/// </summary>
/// <param name="filepath">文件路径</param>
/// <returns>Json内容</returns>
private string GetJsonFile(string filepath)
{
string json = string.Empty;
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
json = sr.ReadToEnd().ToString();
}
}
return json;
}
写入和读取TXT文件
写入:
cs
/// <summary>
/// 向txt文件中写入字符串
/// </summary>
/// <param name="value">内容</param>
/// <param name="isClearOldText">是否清除旧的文本</param>
private void Wriete(string value, bool isClearOldText = true)
{
string path = "txt文件的路径";
//是否清空旧的文本
if (isClearOldText)
{
//清空txt文件
using (FileStream stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write))
{
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);
}
}
//写入内容
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(value);
}
}
读取:
cs
/// <summary>
/// 读取txt文件,并返回文件中的内容
/// </summary>
/// <returns>txt文件内容</returns>
private string ReadTxTContent()
{
try
{
string s_con = string.Empty;
// 创建一个 StreamReader 的实例来读取文件
// using 语句也能关闭 StreamReader
using (StreamReader sr = new StreamReader("txt文件的路径"))
{
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
s_con += line;
}
}
return s_con;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
打开一个弹框,选择 文件/文件夹,并获取路径
注意,选择文件和选择文件夹的用法不一样
选择文件夹
cs
System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.Description = "请选择文件夹";
dialog.SelectedPath = "C:\\";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Console.WriteLine("选择了文件夹路径:" + dialog.SelectedPath);
}
选择文件
cs
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;//该值确定是否可以选择多个文件
dialog.Title = "请选择文件";
dialog.Filter = "所有文件(*.*)|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Console.WriteLine("选择了文件路径:" + dialog.FileName);
}
限制文件的类型
例1:
cs
OpenFileDialog dialog = new OpenFileDialog();
//该值确定是否可以选择多个文件
dialog.Multiselect = false;
dialog.Title = "请选择文件";
dialog.Filter = "stp文件|*.stp|step文件|*.STEP|所有文件|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = dialog.FileName;
}
例2:
cs
OpenFileDialog dialog = new OpenFileDialog();
//该值确定是否可以选择多个文件
dialog.Multiselect = false;
dialog.Title = "请选择文件";
dialog.Filter = "图像文件|*.jpg*|图像文件|*.png|所有文件|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = dialog.FileName;
}
保存文件
保存文件,用的是 SaveFileDialog
代码
cs
SaveFileDialog s = new SaveFileDialog();
s.Filter = "图像文件|*.jpg|图像文件|*.png|所有文件|*.*";//保存的文件扩展名
s.Title = "保存文件";//对话框标题
s.DefaultExt = "图像文件|*.jpg";//设置文件默认扩展名
s.InitialDirectory = @"C:\Users\Administrator\Desktop";//设置保存的初始目录
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = s.FileName;
}
获取项目的Debug目录路径
控制台程序:
cs
string path = Environment.CurrentDirectory;
Winform:
cs
string path = Application.StartupPath;
WPF:
cs
string path = AppDomain.CurrentDomain.BaseDirectory;
获取一个目录下的所有文件集合
cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
//文件夹列表
private static List<string> DirectorysList = new List<string>();
//文件列表
private static List<string> FilesinfoList = new List<string>();
static void Main(string[] args)
{
//路径
string path1 = Environment.CurrentDirectory + "\\Test1";
GetDirectoryFileList(path1);
Console.ReadKey();
}
/// <summary>
/// 获取一个文件夹下的所有文件和文件夹集合
/// </summary>
/// <param name="path"></param>
private static void GetDirectoryFileList(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
FileSystemInfo[] filesArray = directory.GetFileSystemInfos();
foreach (var item in filesArray)
{
//是否是一个文件夹
if (item.Attributes == FileAttributes.Directory)
{
DirectorysList.Add(item.FullName);
GetDirectoryFileList(item.FullName);
}
else
{
FilesinfoList.Add(item.FullName);
}
}
}
}
}
获取文件全路径、目录、扩展名、文件名称
代码:
cs
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
//获取当前运行程序的目录
string fileDir = Environment.CurrentDirectory;
Console.WriteLine("当前程序目录:" + fileDir);
//一个文件目录
string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml";
Console.WriteLine("该文件的目录:" + filePath);
string str = "获取文件的全路径:" + Path.GetFullPath(filePath); //-->C:\JiYF\BenXH\BenXHCMS.xml
Console.WriteLine(str);
str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH
Console.WriteLine(str);
str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //-->BenXHCMS.xml
Console.WriteLine(str);
str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS
Console.WriteLine(str);
str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.xml
Console.WriteLine(str);
str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\
Console.WriteLine(str);
Console.ReadKey();
}
}
读取当前的文件夹名
cs
using System;
using System.Collections.Generic;
using System.IO;
namespace ListTest
{
internal class Program
{
static void Main(string[] args)
{
string fileDir = Environment.CurrentDirectory;
DirectoryInfo dirInfo = new DirectoryInfo(fileDir);
string currentDir = dirInfo.Name;
Console.WriteLine(currentDir);
string dirName = System.IO.Path.GetFileNameWithoutExtension(fileDir);
Console.WriteLine(dirName);
Console.ReadKey();
}
}
}
运行:
判断两个文件是否相同
cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace 判断两个文件是否相同
{
class Program
{
static void Main(string[] args)
{
//路径
string path1 = Environment.CurrentDirectory + "\\Test1\\文件1.txt";
string path2 = Environment.CurrentDirectory + "\\Test2\\文件1.txt";
bool valid = isValidFileContent(path1, path2);
Console.WriteLine("这两个文件是否相同:" + valid);
Console.ReadKey();
}
public static bool isValidFileContent(string filePath1, string filePath2)
{
//创建一个哈希算法对象
using (HashAlgorithm hash = HashAlgorithm.Create())
{
using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
{
byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根据文本得到哈希码的字节数组
byte[] hashByte2 = hash.ComputeHash(file2);
string str1 = BitConverter.ToString(hashByte1);//将字节数组装换为字符串
string str2 = BitConverter.ToString(hashByte2);
return (str1 == str2);//比较哈希码
}
}
}
}
}
判断文件路径或文件是否存在
判断文件夹是否存在:
cs
string path = Application.StartupPath + "\\新建文件夹";
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}
判断文件是否存在:
cs
string path = Application.StartupPath + "\\新建文件夹\\test.txt"
if(System.IO.File.Exists(path))
{
Console.WriteLine("存在该文件");
}
else
{
Console.WriteLine("不存在该文件");
}
判断一个路径是文件夹还是文件
方式1
cs
/// <summary>
/// 判断目标是文件夹还是目录(目录包括磁盘)
/// </summary>
/// <param name="filepath">路径</param>
/// <returns>返回true为一个文件夹,返回false为一个文件</returns>
public static bool IsDir(string filepath)
{
FileInfo fi = new FileInfo(filepath);
if ((fi.Attributes & FileAttributes.Directory) != 0)
{
return true;
}
else
{
return false;
}
}
方式2
cs
if (File.Exists(add_file))
{
Console.WriteLine("是文件");
}
else if (Directory.Exists(targetPath))
{
Console.WriteLine("是文件夹");
}
else
{
Console.WriteLine("都不是");
}
end