前言
文件操作是开发过程中经常遇到的,如何创建文件、处理文件、保存文件以及读取文件这些工作是每一位开发都必须经历的。
这里围绕C#文件操作内容,我做了一次系统的梳理,主要包括以下几个模块:
1、文件内容操作:文件读写相关
2、文件检测
3、文件及目录创建和删除
4、文件移动
5、文件加密、解密
6、文件上传、下载
7、文件压缩相关
8、文件操作权限相关
一、小节摘要
本节主要讲文件操作权限相关内容,主要包括一下方面:
1、文件是否存在或无权访问 FileIsExist(string path)
2、文件是否只读 FileIsReadOnly(string fullpath)
3、设置文件是否只读 SetFileReadonly(string fullpath, bool flag)
4、取文件名 GetFileName(string fullpath, bool removeExt)
5、取文件创建时间 GetFileCreateTime(string fullpath)
6、取文件最后存储时间 GetLastWriteTime(string fullpath)
7、获取指定文件详细属性 GetFileAttibe(string filePath)
二、详细内容
1、文件是否存在或无权访问 FileIsExist(string path)
public static bool FileIsExist(string path)
{
return File.Exists(path);
}
2、文件是否只读 FileIsReadOnly(string fullpath)
public static bool FileIsReadOnly(string fullpath)
{
FileInfo file = new FileInfo(fullpath);
if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
return true;
}
else
{
return false;
}
}
3、设置文件是否只读 SetFileReadonly(string fullpath, bool flag)
public static void SetFileReadonly(string fullpath, bool flag)
{
FileInfo file = new FileInfo(fullpath);
if (flag)
{
// 添加只读属性
file.Attributes |= FileAttributes.ReadOnly;
}
else
{
// 移除只读属性
file.Attributes &= ~FileAttributes.ReadOnly;
}
}
4、取文件名 GetFileName(string fullpath, bool removeExt)
public static string GetFileName(string fullpath, bool removeExt)
{
FileInfo fi = new FileInfo(fullpath);
string name = fi.Name;
if (removeExt)
{
name = name.Remove(name.IndexOf('.'));
}
return name;
}
5、取文件创建时间 GetFileCreateTime(string fullpath)
public static DateTime GetFileCreateTime(string fullpath)
{
FileInfo fi = new FileInfo(fullpath);
return fi.CreationTime;
}
6、取文件最后存储时间 GetLastWriteTime(string fullpath)
public static DateTime GetLastWriteTime(string fullpath)
{
FileInfo fi = new FileInfo(fullpath);
return fi.LastWriteTime;
}
7、获取指定文件详细属性 GetFileAttibe(string filePath)
public static string GetFileAttibe(string filePath)
{
string str = "";
FileInfo objFI = new FileInfo(filePath);
str += "详细路径:" + objFI.FullName
+ "<br>文件名称:" + objFI.Name
+ "<br>文件长度:" + objFI.Length.ToString()
+ "字节<br>创建时间" + objFI.CreationTime.ToString()
+ "<br>最后访问时间:" + objFI.LastAccessTime.ToString()
+ "<br>修改时间:" + objFI.LastWriteTime.ToString()
+ "<br>所在目录:" + objFI.DirectoryName
+ "<br>扩展名:" + objFI.Extension;
return str;
}