C# 操作文件夹、文件流

目录操作

 

string[] drives = Directory.GetLogicalDrives();   //本地驱动器的名,如:C:\等

 

string path = Directory.GetCurrentDirectory();  //获取应用程序的当前工作目录

 

Path.GetFileName(@"c:\dir\file.txt"); //获取子目录的名字,result的结果是file.txt

 

Directory.GetFiles(路径及文件名)                     //获取指定目录中的文件名(文件列表)

 

DirectoryInfo di = new DirectoryInfo(@"f:\MyDir");      //构造函数创建目录

 

DirectoryInfo di=Directory.CreateDirectory(@"f:\bbs"); //创建对象并创建目录

 

if (di.Exists == false)                                    //检查是否存在此目录

 

{  di.Create();  } //创建目录

 

DirectoryInfo dis = di.CreateSubdirectory("SubDir");    //以相对路径创建子目录

 

dis.Delete(true);                                         //删除刚创建的子目录

 

di.Delete(true);                                          //删除创建目录

 

 

 

文件操作

 

Directory.Delete(@"f:\bbs2", true); //删除目录及其子目录和内容(如为假不能删除有内容的目录包括子目录)

 

Directory.GetDirectories 方法 //获取指定目录中子目录的名称

 

string[] dirs = Directory.GetDirectories(@"f:\", "b*"); Console.WriteLine("此目录中以b开头的子目录共{0}个!", dirs.Length);

 

foreach (string dir in dirs) { Console.WriteLine(dir); }

 

Directory.GetFileSystemEntries //获取指定目录中的目录及文件名

 

Directory.GetLogicalDrives //检索此计算机上格式为“<驱动器号>:\”的逻辑驱动器的名称,【语法同上】

 

Directory.GetParent //用于检索父目录的路径。

 

DirectoryInfo a = Directory.GetParent(path);

 

Console.WriteLine(a.FullName);

 

Directory.Move //移动目录及其在内的所有文件

 

Directory.Move(@"f:\bbs\1", @"f:\bbs\2"); //将文件夹1内的文件剪到文件夹2内 文件夹2是刚创建的(即在程序执行的时候,文件夹2是不存在的)

 

 文件流操作

 

// 对字节的读写操作(包含对异步操作的支持) Reading Writing Seeking
BinaryReader和BinaryWriter // 从字符串或原始数据到各种流之间的读写操作

 

FileStream类通过Seek()方法进行对文件的随机访问,默认为同步

 

TextReader和TextWriter //用于gb2312字符的输入和输出

 

StringReader和StringWriter //在字符串中读写字符

 

StreamReader和StreamWriter //在流中读写字符

 

BufferedStream 为诸如网络流的其它流添加缓冲的一种流类型.

 

MemoryStream 无缓冲的流

 

NetworkStream 互联网络上的流

编码转换

 

Encoding e1 = Encoding.Default;               //取得本页默认代码

 

Byte[] bytes = e1.GetBytes("中国人民解放军"); //转为二进制

 

string str = Encoding.GetEncoding("UTF-8").GetString(bytes); //转回UTF-8编码

 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  例:修改文件名称、文件夹名称                                                                                                                                                                                                          

 

            string srcFileName = @"D:/a.txt";

            string destFileName = @"D:/b.txt";

 

            string srcFolderPath = @"D:/1";

            string destFolderPath = @"D:/6";

            

            //方法一  

            if (System.IO.File.Exists(srcFileName))

            {

                System.IO.File.Move(srcFileName, destFileName);

            }

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

            {

                System.IO.Directory.Move(srcFolderPath, destFolderPath);

            }

            

            //方法二 

            if (System.IO.File.Exists(srcFileName))

            {

                System.IO.FileInfo file = new System.IO.FileInfo(srcFileName);

                file.MoveTo(destFileName);

            }

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

            {

                System.IO.DirectoryInfo folder = new System.IO.DirectoryInfo(srcFolderPath);

                folder.MoveTo(destFolderPath);

            }

 

 

C# 重命名本地硬盘的文件名

1.先在项目中添加引用:Microsoft.VisualBasic  

然后在所需使用的文档中加上using Microsoft.VisualBasic.Devices; 命名空间

2.就下面两行                

Computer MyComputer = new Computer();                

MyComputer.FileSystem.RenameFile(FileName, newFileName);


其中FileName是你所要重命名的文件的全路径,newFileName仅仅是目标文件名;

 

创建文件夹

要实现的功能:在IIS服务器上创建文件夹,用来存放工厂生产的数据,文件夹目录按照UserData/DCCFile/year/mounth/filename的方式创建。当用户存文件的时候查找是否存在此文件夹,不存在的时候则先创建文件夹,然后进行上传文件。

实现逻辑:预先设定一个虚拟路径,用server.mappath()将文件要存放的相对路径映射到绝对路径,然后用Directory类在绝对路径中创建文件夹,然后将文件上传到此绝对路径中。

实现代码:

 string stryear = System.DateTime.Now.Year.ToString();

string strmonth = System.DateTime.Now.Month.ToString();

string path = Server.MapPath("~/UserData/DCCFile/"+stryear+"/"+strmonth+"/");//文件要上传到的虚拟路径

//path为经过映射的在本地磁盘上的绝对路径

if (!Directory.Exists(path))//判断这个绝对路径是否存在

{
                    Directory.CreateDirectory(path); //不存在文件夹时则创建文件夹
                }

FileUpload1.SaveAs(path+FileUpload1.FileName);//上传新文件

 

 

         例:一个文件下载示例

 

            string filename="文件名";

 

           string serverpath = System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/UserData/DCCFile/" + stryear + "/" + strmonth + "/" + strSysFileNumber + "/");//MeThod1:从ISS服务器映射文件的绝对路径

 

           string serverpath=Server.MapPath("~/UserData/DCCFile/" + stryear + "/" + strmonth + "/" + strSysFileNumber + "/");//MeThod2:从ISS服务器映射文件的绝对路径

            string fileFullName = serverpath + filename;//文件的全名

            FileInfo file = new FileInfo(fileFullName);

            if (File.Exists(fileFullName))

            {

                //将文件下载到客户机

                Response.Clear();

                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));

                Response.ContentType = "application/octet-stream";

                Response.Filter.Close(); //Response.Filter 是一个 Stream 对象(表示字节序列的流),Response.Filter.CLose() 表示关闭此流对象并释放相关资源。

                Response.WriteFile(file.FullName);

                Response.End();

            }

            else

            {

                Page.ClientScript.RegisterStartupScript(GetType(), "alert", "");

            }

 

 

说明:application/octet-stream 是一种MIME类型,表示可以实现任何格式的文件下载

Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。

我们在开发web系统时有时会有以下需求:
希望某类或者某已知MIME 类型的文件(比如:*.gif;*.txt;*.htm)能够在访问时弹出“文件下载”对话框
希望以原始文件名(上传时的文件名,例如:山东省政府1024号文件.doc)提供下载,但服务器上保存的地址却是其他文件名(如12519810948091234_asdf.doc)
希望某文件直接在浏览器上显示而不是弹出文件下载对话框

解决办法是 Response.AddHeader "content-disposition","attachment; filename=fname.ext"

将上述需求进行归我给出如下例子代码:
public static void ToDownload(string serverfilpath,string filename)
{
    FileStream fileStream = new FileStream(serverfilpath, FileMode.Open);
    long fileSize = fileStream.Length;
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + UTF_FileName(filename) + "\";");
    ////attachment --- 作为附件下载
    ////inline --- 在线打开
    HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
    byte[] fileBuffer = new byte[fileSize];
    fileStream.Read(fileBuffer, 0, (int)fileSize);
    HttpContext.Current.Response.BinaryWrite(fileBuffer);
    fileStream.Close();
    HttpContext.Current.Response.End();
}

private static string UTF_FileName(string filename)
{
    return HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
}

UTF_FileName方法 主要为了解决包含非英文/数字名称的问题,比如说文件名为“衣明志.doc”,使用该方法客户端就不会出现 乱码了。作用同上面的Server.UrlEncode

 


 

你可能感兴趣的:(C#)