//读取文件到二进制
static public Byte[] ReadFile2Byte(String filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
long size = fs.Length;
byte[] array = new byte[size];
fs.Read(array, 0, array.Length);//将文件读到byte数组中
fs.Close();
return array;
}
//读取文件到string
static public string ReadFile2String(String filePath)
{
return File.ReadAllText(filePath, Encoding.GetEncoding("gb2312"));
}
//追加写文件-二进制
static public void WriteByte2File(String filePath,Byte[] bytes)
{
System.IO.FileStream dataWriter = new System.IO.FileStream(filePath, System.IO.FileMode.Append);
dataWriter.Seek(0, System.IO.SeekOrigin.End);
dataWriter.Write(bytes, 0, bytes.Length);
dataWriter.Flush();
dataWriter.Close();
}
//追加写文件-text
static public void WriteByte2File(String filePath, string texts)
{
StreamWriter sw = new StreamWriter(filePath, true, Encoding.GetEncoding("gb2312"));
sw.Write(texts);
sw.Close();
}
//读取一个文件夹下的所有文件-路径以最后一个文件夹开头的相对路径
static public List<String> FileRead(String basePath)
{
List<String> fileList = new List<string>();
try
{
var fd = Path.GetFullPath(basePath);
fd = fd.Replace("\\", "/");
fd = fd.Substring(fd.LastIndexOf("/"));
DirectoryInfo dirInfo = new DirectoryInfo(basePath);
FileRead(basePath, fd, dirInfo, ref fileList);
}
catch
{
}
return fileList;
}
//遍历一个文件夹下的所有文件
static public void FileRead(String basePath, String fd, DirectoryInfo dirInfo, ref List<String> fileList)
{
var fs = dirInfo.GetFiles();
for (var i = 0; i < fs.Length; i++)
{
var filePath = fs[i].FullName.Substring(Path.GetFullPath(basePath).Length).Replace("\\", "/");
fileList.Add(fd + filePath);
}
var ds = dirInfo.GetDirectories();
for (var i = 0; i < ds.Length; i++)
{
FileRead(basePath, fd, ds[i], ref fileList);
}
}
//路径相关
7 string fileDir = Environment.CurrentDirectory;
8 Console.WriteLine("当前程序目录:"+fileDir);
9
10 //一个文件目录
11 string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml";
12 Console.WriteLine("该文件的目录:"+filePath);
13
14 string str = "获取文件的全路径:" + Path.GetFullPath(filePath); //-->C:\JiYF\BenXH\BenXHCMS.xml
15 Console.WriteLine(str);
16 str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH
17 Console.WriteLine(str);
18 str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //-->BenXHCMS.xml
19 Console.WriteLine(str);
20 str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS
21 Console.WriteLine(str);
22 str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.xml
23 Console.WriteLine(str);
24 str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\
25 Console.WriteLine(str);
26 Console.ReadKey();
1766

被折叠的 条评论
为什么被折叠?



