很久没有写博客了,之前很长一段时间忙于毕设和找工作,现在工作了,觉得自己还有很多不足,书到用时方恨少,在进行项目时会遇到很多问题,感谢各位博客大牛的技术分享,也顺利完成了自己的功能任务,下面针对C#中文件读写问题进行一些总结。
1.最简单的一种文件拷贝和剪切方式
string SourcePath =“源文件全路径”;
string TargetPath = “目标文件全路径”;
System.IO.File.Copy(SourcePath, TargetPath); //拷贝
System.IO.File.Move(SourcePath, TargetPath); //剪切
System.IO.File.Delete(SourcePath); //删除
2.以文件流的方式读写文件,以读写图片为例,从一个文件夹拷到另一个指定文件夹3
string PicPath = “目标图片保存路径”;
string Soursename = “源图片的文件夹”
if (string.IsNullOrEmpty(Soursename))
{
Log.ErrorFormat("Get FTP picture path failed. deviceName={0}");
}
if (string.IsNullOrEmpty(PicPath))
{
Log.ErrorFormat("Generate picture path failed. deviceName={0}");
}
DirectoryInfo mydir = new DirectoryInfo(Soursename); //建一个文件夹对象
foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos()) //遍历源保存文件路径中的文件
{
if (fsi is FileInfo)
{
FileInfo fi = (FileInfo)fsi;
string x = System.IO.Path.GetDirectoryName(fi.FullName);
string s = System.IO.Path.GetExtension(fi.FullName); //文件后缀名
string y = System.IO.Path.GetFileNameWithoutExtension(fi.FullName);
if (s == ".jpg") //筛选出jpg格式的文件
{
string Fillalname = “生成的目标文件名称”
byte[] buffer = null;
buffer = Readpic(fi.FullName); //从FTP保存路径读操作
string Picfullname =“目标文件全路径”;
FileStream fs = new FileStream(Picfullname, FileMode.Create); //从流中保存文件到本地
fs.Write(buffer, 0, buffer.Length); //写操作
fs.Dispose();
}
}
}
读文件方法:
public byte[] ReadFTPpic(string filepath) //从FTP保存路径读操作
{
FileStream fs = null;
byte[] buffer = null;
try
{
if (File.Exists(filepath)) //图片文件的全路径字符串
{
fs = new FileStream(filepath, FileMode.Open);
buffer = new byte[fs.Length];
fs.Read(buffer, 0, int.Parse(fs.Length.ToString()));
fs.Close();
fs.Dispose();
}
}
catch
{
fs.Close();
fs.Dispose();
}
return buffer;//图片文件的流
}
3.判断文件的占用状态
在进行源目标文件夹遍历,读写文件时,当源文件被占用时,这时想再次操作源文件,对其进行读操作是不允许的,加入异常处理发现抛出异常,这次的读操作并没有执行,这时应该加入判断文件占用状态,并可做出相应的处理。
代码如下:
public static class FileControlRepository1
{
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);//调用windowsdll
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);//调用windowsdll
public const int OF_READWRITE = 2;//这些参数是不可少的,当然也可以不声明,直接将值赋值给对应的函数,这里只是生明变量将其存起来而已
public const int OF_SHARE_DENY_NONE = 0x40;//这些参数是不可少的,当然也可以不声明,直接将值赋值给对应的函数,这里只是生明变量将其存起来而已
public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
public static int IsFileOpen(string path)
{
string vFileName = path;
if (!File.Exists(vFileName))
{
return 0;//文件不存在
}
IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);//windows Api上面有定义扩展方法
if (vHandle == HFILE_ERROR)
{
return 2;//文件被占用
}
CloseHandle(vHandle);//windows Api上面有定义扩展方法
return 1;//文件存在且没被占用
}
}
4.Substring方法
string = filename;
int index = filename.IndexOf("_"); //定位文件名一次出现“_”的地方
index = filename.IndexOf("_", index + 1); //第二次
string name = y.Substring(index+1, 14); //截取第二次出现“_”后的14字符