c#中的文件操作

DirectoryInfo ,FileInfo用于创建,删除,修改文件夹和文件  File和StreamReader,StreamWriter用来操作文件内容

//创建文件夹test
        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("test"));
        if (!dir.Exists)
        {
            //dir.CreateSubdirectory("test");
            dir.Create();
        }
        else
        {
            Response .Write ("<script language='javascript'>alert('文件夹hello已经存在');</script>");
        }
//创建文件test.txt
         FileInfo fi = new FileInfo(Server.MapPath("test") + @"/test.txt");
        if (fi.Exists)
        {
            Response.Write("<script language='javascript'>alert('创建时间为:" + fi.CreationTime.ToString() + "');</script>");
        }
        else
        {
            fi.Create();
        }
//写入文件test.txt
        StreamWriter sw = File.AppendText(Server.MapPath("test") + @"/test.txt");
        sw.Write("this is a test");
        sw.Close();
//读取文件test.txt

StreamReader sr = File.OpenText(Server.MapPath("test") + @"/test.txt");
        string str = sr.ReadLine();
        sr.Close();
        Response.Write(str);

//访问文件夹所有文件

string str = "";

        DirectoryInfo dir;
        FileInfo fi;

        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("test"));
        foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())
        {
            if (fsi is FileInfo)
            {
                fi = (FileInfo)fsi;
                //访问文件的属性
                str = str + fi.Name  + "<br/>";
            }
            else
            {
                dir = (DirectoryInfo)fsi;
                //访问文件夹的属性
                str = str + dir.Name + "<span style='color: #ff0066'>文件夹</span><br/>";
            }
        }

        Response.Write(str);

你可能感兴趣的:(文件操作)