zoukankan      html  css  js  c++  java
  • c#操作 文件操作

    需要using System.IO 命名空间

    从文本文件中读取内容:

    public string readtxts(string path){
    StreamReader sr=new StreamReader(Server.MapPath(path),System.Text.Encoding.Default);
    string input =sr.ReadToEnd();
    return input;
    }

    调用方法:

    string path = "10.txt";//文件名称
    Response.Write(readtxts(path));

    拷贝文件:

    string paths = HttpContext.Current.Server.MapPath("10.txt");
    string pathd = HttpContext.Current.Server.MapPath("11.txt");
    File.Copy(paths,pathd);

    移动文件:

    string paths = HttpContext.Current.Server.MapPath("10.txt");
    string pathd = HttpContext.Current.Server.MapPath("10copys.txt");
    File.Move(paths,pathd);

    向文本文件中写入内容:

    //文件路径方法1
    string path=Server.MapPath(".")+("\\10.txt");
    //文件路径方法2
    string paths=HttpContext.Current.Server.MapPath("10.txt");
    
    StreamWriter sw=File.AppendText(path);
    sw.WriteLine("Hello");
    sw.Flush();
    sw.Close();

    删除文件:

    string paths = HttpContext.Current.Server.MapPath("10.txt");
    File.Delete(paths);

    建立一个文件:

    string paths = HttpContext.Current.Server.MapPath("10.txt");
    File.Delete(paths);
    File.Create(paths);

    建立一个目录:

    string paths = HttpContext.Current.Server.MapPath("readbook");
    Directory.CreateDirectory(paths);

     删除目录:

    string paths = HttpContext.Current.Server.MapPath("readbook");
    Directory.Delete(paths)

     建立目录:

    string paths = HttpContext.Current.Server.MapPath("sssss");
    DirectoryInfo d = Directory.CreateDirectory(paths);
    DirectoryInfo d1 = d.CreateSubdirectory("ddd");

     递归删除文件及文件夹:

    public void deletefloder(string dir)
        {
    
            if (Directory.Exists(dir))
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d);
                    else
                        deletefloder(d);
                    Response.Write(d);
                }
                Directory.Delete(dir);
                Response.Write(dir + "删除成功");
            }
            Response.Write("没有这个文件");
        }
  • 相关阅读:
    OO设计的开闭原则
    OO设计的接口分隔原则
    玩大数据需要知道的12个工具
    怎么回答哪个更快的问题
    C#用extern alias解决两个assembly中相同的类型全名
    CoffeeScript, Ruby 和 C++的复杂度比较
    用python替代javascript?
    C#的内存模型和并发情况下受到的影响
    怎么看C++对象的内存结构 和 怎么解密C++的name mangling
    .NET中使用Unity和StructureMap来实现依赖注入Dependency Injection
  • 原文地址:https://www.cnblogs.com/yzhang/p/2725172.html
Copyright © 2011-2022 走看看