• .NET对文件的多种操作


      要提到对文件的操作,那么自然就会有一下几种方式:

        那么首先我肯定要去找到我要操作的文件夹,请看如下代码

        遍历文件夹找到目标文件

            //获取你代码的物理路径(是指到你当前的页面这一级)
    string path = this.Request.PhysicalApplicationPath;
    //添加具体准确路径
    string realpath = path + "Web/DataImport/DataBackup";
    //替换路径格式
    string newpath = realpath.Replace("\\", "/");
    //获取该路径文件及下面的所有文件名并存储到数组中
    string[] filename = Directory.GetFiles(newpath);

        此时将该文件下面的所有完整文件路径都保存在数组当中,那么此时如果你想得到该文件下面有多少个文件,是不是直接length=filename.length就可以了

        接下来我想将文件进行复制一份

               复制文件到指定位置

    1         //定义复制的存储路径
    2 string varToDirectory = path;
    3 if (filename.Length > 0)
    4 {
    5 foreach (string s in filename)
    6 {
    7 File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")));
    8 }
    9 }


         那么现在我想对这些文件压缩打包,然后下载到本地:

             于是乎,你可以调用这个函数来压缩你的文件并可指定存储路径

     1 //patch文件/文件夹 路径,rarPatch  rar存储路径, rarName保存的文件夹名称
    2
    3 public void RARsave(string patch, string rarPatch, string rarName)
    4 {
    5
    6 String the_rar;
    7
    8 RegistryKey the_Reg;
    9
    10 Object the_Obj;
    11
    12 String the_Info;
    13
    14 ProcessStartInfo the_StartInfo;
    15
    16 Process the_Process;
    17
    18 try
    19 {
    20
    21 the_Reg = Registry.ClassesRoot.OpenSubKey(@"WinRAR");
    22
    23 the_Obj = the_Reg.GetValue("");
    24
    25 the_rar = the_Obj.ToString();
    26
    27 the_Reg.Close();
    28
    29 the_rar = the_rar.Substring(1, the_rar.Length - 7);
    30 if (!Directory.Exists(patch))
    31 {
    32 Directory.CreateDirectory(patch);
    33 }
    34
    35
    36 //the_Info = " a " + rarName + " " + @"C:Test?70821.txt"; \\文件压缩
    37
    38 the_Info = " a " + rarName + "" + patch + " -r";
    39
    40 the_StartInfo = new ProcessStartInfo();
    41
    42 the_StartInfo.FileName = "WinRar";//the_rar;
    43
    44 the_StartInfo.Arguments = the_Info;
    45
    46 the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    47
    48 //打包文件存放目录
    49
    50 the_StartInfo.WorkingDirectory = rarPatch;
    51
    52 the_Process = new Process();
    53
    54 the_Process.StartInfo = the_StartInfo;
    55
    56 the_Process.Start();
    57
    58 the_Process.WaitForExit();
    59
    60 the_Process.Close();
    61
    62 }
    63
    64 catch (Exception ex)
    65 {
    66
    67 throw ex;
    68
    69 }
    70
    71 }

              哎呀呀,现在文件也操作了,我觉得他没用了,我就想把它给删除了

              对指定的文件删除掉

    1        if (filename.Length > 0)
    2 {
    3 foreach (string s in filename)
    4 {
    5 File.Delete(s);
    6 }
    7 }

             嗯,做了这些工作,那么接下来的工作就交给你了,至于你想用那些操作,那就根据你的需要吧!


               

  • 相关阅读:
    Django —— DateTimeField格式
    Django——权限组件(中间件判断用户权限--URL初级)
    linux命令
    性能测试--测试分类
    web安全之csrf攻击
    web安全之xss攻击
    测试用例规范
    禅道操作手册
    fiddler弱网测试
    Web测试系列之测试工具
  • 原文地址:https://www.cnblogs.com/xiaopanlyu/p/2415562.html
Copyright © 2020-2023  润新知