1、判断文件是否存在
判断文件是否存在,主要调用的是File.Exists函数。
private bool is_exist(string file_path) {
if (File.Exists(file_path)) {
return true;
} else {
return false;
}
}
2、判断文件是否正在使用
判断文件是否正在使用主要使用的是一个try{ } catch(){}的使用,实际上在后续的使用中越来越感受到的是try{}catch使用的重要性。
可以给我们处理掉很多的异常处理。
static private bool is_inuse(string filePath) {
bool file_in_use = true;
FileStream fs = null;
try {
fs = new FileStream(filePath, FileMode.Open,FileAccess.Read,FileShare.None); // if is in use we come to catch
file_in_use = false;
}catch(Exception e){
file_in_use = true;
}
finally {
if (fs != null) {
fs.Close();
}
}
return file_in_use;
}
3、判断文件是否是指定类型的文件,最直观的方式是通过文件名来做判断,但感觉从文件头来进行分析才是标准做法
static private bool is_excle(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] header = new byte[4];
string temstr = "";
// Writes a file header stream to a byte array
if (Convert.ToInt32(fs.Length) > 0){
fs.Read(header, 0, 4);
fs.Close();
for (int i = 0; i < header.Length; i++){
// Convert to 16
temstr += header[i].ToString("X2");
}
}
if (temstr.ToUpper() == "504B0304"){
return true;
}else{
return false;
}
}
文件头可以在往上搜索,也可以使用
windhex
开分析他的文件头,前面的四位即是文件头,一般需要注意的是16进制10以下需要将前面的0补齐