C#关于文件的判断

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补齐

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值