System.IO命名空间

使用 System.IO 和 Visual C# .NET 读取文本文件

在 Visual C# .NET 中读取文本文件 打开和读取文件进行读取访问是输入/输出 (IO) 功能的一个非常重要的部分,即使您不需要写入到相关文件,也是如此http://www.alixixi.com/Dev/Web/ASPNET/aspnet3/2007/2007050734418.html

确保项目至少引用了 System 命名空间。对 System、System.IO 和 System.Collections 命名空间使用 using 语句,这样以后就无需在代码中限定这些命名空间中的声明。这些语句必须位于任何其他声明之前。http://support.microsoft.com/kb/306777/zh-cn

1、Form 与 QueryString 集合对象

    如果网页用Post 方法传递数据的,用Form获取数据(使用窗体或页面通过点击按钮提交的):

    语法:Request("FileName")

          Request.Form("FileName")(两种均可取值)

    如果页面有两个或以上相同的名的Text则要使用GetValues()方法+index(序号)获取

    语法:Request.Form.GetValues("FileName")(index)

      例:Request.Form.GetValues("UserName")(0)

          Request.Form.GetValues("UserName")(1)

    如果网页用Get方法传递数据的,用QueryString 获取数据(通过网页传递的参数):

    语法:Request("FileName")

          Request.QueryString ("FileName")

    如果页面有两个或以上相同的名的Text则要使用GetValues()方法+index(序号)获取

    语法:Request.QueryString .GetValues("FileName")(index)

      例:Request.QueryString .GetValues("UserName")(0)

          Request.QueryString .GetValues("UserName")(1)

2、设置中文编码 (ASP.NET默认为UTF-8,可以WEB.config配置文件设置中文编码)

   <configuration>

     <system.web>

       <globalization//此标记为指定默认编码方式和语种

        fileEncoding="gb2312"//设置编码方式

        requestEncoding="gb2312"//设置Request对象获取数据的编码方式

        responseEncoding="gb2312"//Response对象发送数据的编码方式

        culture="zh-CN"//指定国的语系,zh-CN为中国

       />

     </system.web>

   </configuration>

3、显示磁盘的相关信息

   DriveInfo[] allDrives = DriveInfo.GetDrives();

   foreach (DriveInfo d in allDrives)

   {

     Response.Write("Drive:"+ d.Name +"<BR>");

     Response.Write("File type:" + d.DriveType + "bytes <BR>");

     if (d.IsReady == true)

        {

         Response.Write("Volume label:" + d.VolumeLabel + "<BR>");

         Response.Write("File system:" + d.DriveFormat + "<BR>");

         Response.Write("Available space to current user:" + d.AvailableFreeSpace + "bytes<BR>");

         Response.Write("Total available space:" + d.TotalFreeSpace + "bytes<BR>");

         Response.Write("Total size of drive:" + d.TotalSize + "bytes <P>");

        }

    }

4、使用TreeView显示本地磁盘的两种方式:

        TreeNode node = new TreeNode("我的电脑");

        this.TreeView1.Nodes.Add(node);

   (1) DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)

            {

                TreeNode drivesNode = new TreeNode(d.Name + "*" + d.VolumeLabel + "*");

                node.ChildNodes.Add(drivesNode);//添加到节点

            }

          //d.VolumeLabel 为对应磁盘的卷标

   (2) string[] str = Directory.GetLogicalDrives();

        for (int k = 0; k < str.Length; k++)

        {

            TreeNode drivesNode = new TreeNode(str[k]);

            node.ChildNodes.Add(drivesNode);

         }

      或

         foreach (DriveInfo k in str)

        {

            TreeNode drivesNode = new TreeNode(k.Name);

            node.ChildNodes.Add(drivesNode);

         }

5、显示文件夹及文件

   DirectoryInfo thisOne = new DirectoryInfo("磁盘");//获取磁盘

   foreach (DirectoryInfo sub in thisOne.GetDirectories())//使用GetDirectories()方法获取文件夹列表

   {

     if (sub.GetDirectories().Length > 0 || sub.GetFiles().Length > 0)

        {

          TreeNode subdirNode = new TreeNode(sub.Name);

          subdirNode.Value = sub.FullName;

          drivesNode.ChildNodes.Add(subdirNode);

        }

   }

   foreach (FileInfo fi in thisOne.GetFiles())

   {

       TreeNode subNode = new TreeNode(fi.Name);

       drivesNode.ChildNodes.Add(subNode);

    }

6、用程序建立文件夹

   方法1(动态建文件夹及子文件夹)

     string dir1 = "images\\" + pecode2;//定义相对路径(文件夹名为pecode2)

     string dir2 = "images\\" + pecode2 + "\\" + penums2;//(在上文件夹中建文件夹penums2)

     if (System.IO.Directory.Exists(Server.MapPath(dir1)) == false)

        {

          System.IO.Directory.CreateDirectory(Server.MapPath(dir1));//(没有就先建父的,再建子文件夹)

          System.IO.Directory.CreateDirectory(Server.MapPath(dir2));

        }

        else

           {

             System.IO.Directory.CreateDirectory(Server.MapPath(dir2));//(存在就建子文件夹)

           }

   方法2

    

     try

        {

            if (System.IO.Directory.Exists(dir1 ))

            {

                MsgLabel.Text = "该文件夹已经存在";

                return;

            }

            else

            {

                System.IO.DirectoryInfo dirinfo = System.IO.Directory.CreateDirectory(dir1 );

                MsgLabel.Text = "成功创建该文件夹!创建时间为:" + System.IO.Directory.GetCreationTime(dir1 );

            }

        }

        catch (Exception ee)

        {

            MsgLabel.Text = "处理失败! 失败的原因是:" + ee.ToString();

        }

7、删除文件夹及下面的文件

  

   public static void DeleteFolder(string dir)

        {

            foreach (string d in Directory.GetFileSystemEntries(dir))

            {

                if (File.Exists(d))

                {

                    FileInfo fi = new FileInfo(d);

                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)

                        fi.Attributes = FileAttributes.Normal;

                    File.Delete(d);//直接删除其中的文件  

                }

                else

                    DeleteFolder(d);//递归删除子文件夹  

            }

            Directory.Delete(dir);//删除已空文件夹  

        }

    protected void Button1_Click(object sender, EventArgs e)//调用

        {

            DeleteFolder("F:\\012");

        }

8、移动文件夹(若文件夹已存在,可选择复盖或先删除再移动过来)

   源文件夹和目标文件夹要求存在于同一个硬盘分区中否则会***作失败

(***作失败! 失败原因:System.IO.IOException: 源路径和目标路径必须具有相同的根。

    移动***作在卷之间无效。 在 System.IO.Directory.Move(String sourceDirName, String destDirName)

    在 CreateDirectory.MoveButton_Click(Object sender, EventArgs e) )

    方法1

    string f1 = "D:\\013";

            string f2 = "F:\\013\\011";

            try

            {

                if (!Directory.Exists(f1))

                {

                    Response.Write("源文件夹不存在!");

                    return;

                }

                if (Directory.Exists(f2))

                {

                    Response.Write("目标文件夹已经存在!");

                    return;

                    //Directory.Delete(f2);删除再建

                    //Directory.Move(f1, f2);

                    //Directory.Move(f1, f2 true); //添加个true 意思是覆盖最好先把文件夹属性设置为空

                   

                }

                Directory.Move(f1, f2);

                Response.Write("文件夹移动成功! 源文件已经被移除。目标文件夹为" + f2);

            }

            catch (Exception ee)

            {

               Response.Write("***作失败! 失败原因:" + ee.ToString());

            }

   方法2(写成方法)

     public bool Mvdir(string FromPath, string ToPath)

        {

            try

            {

                if (!Directory.Exists(ToPath))

                {

                    Directory.Move(FromPath, ToPath);

                    return true;

                }

                else

                {

                    return false;

                }

            }

            catch (exception e)

            {

               return false;

            }

        }

      

        protected void Button1_Click(object sender, EventArgs e)

        {           

            Mvdir("F:\\012", "F:\\011\\012"); //调用

        }

9、对文件的相关***作

   string f1 = "D:\\013\\2.txt";

   string f2 = "F:\\011\\2.txt";

   if (!System.IO.File.Exists(f2))

    {

      //System.IO.File.Copy(f1, f2); //复制文件

      //File.Move(f1, f2); //移动文件

      File.Delete(f1, f2); //删除文件

    }

转一例:

//C#写入/读出文本文件

//注:处理文本的乱码问题

StreamReader sr = new StreamReader(fileName,Encoding.GetEncoding("gb2312"));

  string fileName =@"c:I.txt";

  StreamReader sr = new StreamReader(fileName); string str=sr.ReadLine (); sr.close();

  StreamWriterrw=File.CreateText(Server.MapPath(".")+"/myText.txt");

  rw.WriteLine("写入");

  rw.WriteLine("abc");

  rw.WriteLine(".NET笔记");

  rw.Flush();

  rw.Close();

  //打开文本文件

  StreamReadersr=File.OpenText(Server.MapPath(".")+"/myText.txt");

  StringBuilderoutput=newStringBuilder();

  stringrl;

  while((rl=sr.ReadLine())!=null)

  ...{

  output.Append(rl+"");

  }

  lblFile.Text=output.ToString();

  sr.Close();

  //C#追加文件

  StreamWritersw=File.AppendText(Server.MapPath(".")+"/myText.txt");

  sw.WriteLine("追逐理想");

  sw.WriteLine("kzlll");

  sw.WriteLine(".NET笔记");

  sw.Flush();

  sw.Close();

  //C#拷贝文件

  stringOrignFile,NewFile;

  OrignFile=Server.MapPath(".")+"/myText.txt";

  NewFile=Server.MapPath(".")+"/myTextCopy.txt";

  File.Copy(OrignFile,NewFile,true);

  //C#删除文件

  stringdelFile=Server.MapPath(".")+"/myTextCopy.txt";

  File.Delete(delFile);

  //C#移动文件

  stringOrignFile,NewFile;

  OrignFile=Server.MapPath(".")+"/myText.txt";

  NewFile=Server.MapPath(".")+"/myTextCopy.txt";

  File.Move(OrignFile,NewFile);

  //C#创建目录

  //创建目录c:sixAge

  DirectoryInfod=Directory.CreateDirectory("c:/sixAge");

  //d1指向c:sixAgesixAge1

  DirectoryInfod1=d.CreateSubdirectory("sixAge1");

  //d2指向c:sixAgesixAge1sixAge1_1

  DirectoryInfod2=d1.CreateSubdirectory("sixAge1_1");

  //将当前目录设为c:sixAge

  Directory.SetCurrentDirectory("c:/sixAge");

  //创建目录c:sixAgesixAge2

  Directory.CreateDirectory("sixAge2");

  //创建目录c:sixAgesixAge2sixAge2_1

  Directory.CreateDirectory("sixAge2/sixAge2_1");

 

 

资料引用:http://www.knowsky.com/398825.html

 

原文地址:https://www.cnblogs.com/KimhillZhang/p/1746857.html