C# 文件File (知识点整理)附带上传视频示例方法

1.File类和FileStream文件流

类别

解释

区别

File类

静态类,支持对文件的基本操作,包括创建,拷贝,移动,删除和打开一个文件。File类方法的参量很多时候都是路径Path。主要提供有关文件各种操作,在使用时需要引用System.IO命名空间

是一个文件的类,对文件进行操作;File是笔记本

FileStream文件流

只能处理原始字节(raw byte) FileStream类可以用于任何数据文件,而不仅仅是文本文件。FileStream对象可以用于读取诸如图像和声音的文件,FileStream读取出来的字节数组,然后通过编码转换将字节数组转换成字符串

FileStream文件流,对txt.xml等文件写入内容的时候需要使用的一个工具;FileStream是笔

 

2.File写入文件的方式

FileStream.Write

String filepath=Direction.GetCurrentDirectory()+"\\"+Process.GetCurrentProcess().ProcessName+".txt";

If(File.Exists(filepath))

File.Delete(filepath);

 

FileStream fs = new FileStream(filePath, FileMode.Create);
//获得字节数组
 
string xyPointer = string.Format("X: {0}, Y: {1}", this.Location.X.ToString(), this.Location.Y.ToString());

string highWidth = string.Format("\nW: {0}, H: {1}", this.Width.ToString(), this.Height.ToString());
 byte[] data = System.Text.Encoding.Default.GetBytes(xyPointer + highWidth);
 //开始写入
 fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
 fs.Flush();
 fs.Close();

File.WriteAllLines

 

 

 

//如果文件不存在,则创建;存在则覆盖
22 //该方法写入字符数组换行显示
23 string[] lines = { "first line", "second line", "third line", "第四行" };
24 System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

File.WriteAllText

 

28 //如果文件不存在,则创建;存在则覆盖
29 string strTest = "该例子测试一个字符串写入文本文件。";
30 System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

StreamWriter.Write

 

 

 

34 //在将文本写入文件前,处理文本行
35 //StreamWriter一个参数默认覆盖
36 //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
37 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt", true))
38 {
39 foreach (string line in lines)
40 {
41 if (!line.Contains("second"))
42 {
43 file.Write(line);//直接追加文件末尾,不换行
44 file.WriteLine(line);// 直接追加文件末尾,换行
45 }
46 }
47 }

 

 

 

 

文件操作大全  using System.IO

 

文件夹

 

文件

 

创建

Directory.CreateDirectory();

创建

File.Create();

删除

 

删除

File.Delete();

删除一个目录下所有的文件夹

foreach (string dirStr in Directory.GetDirectories(%%1))
{
 DirectoryInfo dir = new DirectoryInfo(dirStr);
 ArrayList folders=new ArrayList();
 FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
 for (int i = 0; i < folders.Count; i++)
 {
  FileInfo f = folders[i] as FileInfo;
  if (f == null)
  {
   DirectoryInfo d = folders[i] as DirectoryInfo;
   d.Delete();
  }
 }
}

 

 

清空文件夹

Directory.Delete(%%1,true);
Directory.CreateDirectory(%%1);

读取文件

StreamReader s = File.OpenText(%%1);
string %%2 = null;
while ((%%2 = s.ReadLine()) != null){
 %%3
}
s.Close();

 

 

写入文件

FileInfo f = new FileInfo(%%1);
StreamWriter w = f.CreateText();
w.WriteLine(%%2);
w.Close();

 

 

写入随机文件

byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray);
using(FileStream FileStream = new FileStream(%%1, FileMode.Create)){
// Write the data to the file, byte by byte.
 for(int i = 0; i < dataArray.Length; i++){
  FileStream.WriteByte(dataArray[i]);
 }
// Set the stream position to the beginning of the file.
 FileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
 for(int i = 0; i < FileStream.Length; i++){
  if(dataArray[i] != FileStream.ReadByte()){
   //写入数据错误
   return;
  }
 }
//"数据流"+FileStream.Name+"已验证"
}

 

 

读取文件属性

FileInfo f = new FileInfo(%%1);//f.CreationTime,f.FullName
if((f.Attributes & FileAttributes.ReadOnly) != 0){
 %%2
}
else{
 %%3
}

 

 

写入属性

FileInfo f = new FileInfo(%%1);
//设置只读
f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
//设置可写
f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;

枚举一个文件夹中所有文件夹(递归)

foreach (string %%2 in Directory.GetDirectories(%%1)){
 %%3
}

 

 

复制文件夹

string path = (%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2+"\";
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%1 + "\");
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count>0)
{
                    FileSystemInfo tmp = Folders.Dequeue();
                    FileInfo f = tmp as FileInfo;
                    if (f == null)
                    {
                        DirectoryInfo d = tmp as DirectoryInfo;
                        Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
                        foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                        {
                            Folders.Enqueue(fi);
                        }
                    }
                    else
                    {
                        f.CopyTo(f.FullName.Replace(parent, path));
                    }
}

 

 

复制目录下所有的文件夹到另一个文件夹下

 

DirectoryInfo d = new DirectoryInfo(%%1);
foreach (DirectoryInfo dirs in d.GetDirectories())
{
    Queue<FileSystemInfo> al = new Queue<FileSystemInfo>(dirs.GetFileSystemInfos());
    while (al.Count > 0)
    {
        FileSystemInfo temp = al.Dequeue();
        FileInfo file = temp as FileInfo;
        if (file == null)
        {
            DirectoryInfo directory = temp as DirectoryInfo;
            Directory.CreateDirectory(path + directory.Name);
            foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())
                al.Enqueue(fsi);
        }
        else
            File.Copy(file.FullName, path + file.Name);
    }
}

 

 

移动文件夹

 string filename = Path.GetFileName(%%1);
                string path=(%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
                if (Path.GetPathRoot(%%1) == Path.GetPathRoot(%%2))
                    Directory.Move(%%1, path + filename);
                else
                {
                    string parent = Path.GetDirectoryName(%%1);
                    Directory.CreateDirectory(path + Path.GetFileName(%%1));
                    DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%1 + "\");
                    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
                    Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
                    while (Folders.Count > 0)
                    {
                        FileSystemInfo tmp = Folders.Dequeue();
                        FileInfo f = tmp as FileInfo;
                        if (f == null)
                        {
                            DirectoryInfo d = tmp as DirectoryInfo;
                            DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
                            dpath.Create();
                            foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                            {
                                Folders.Enqueue(fi);
                            }
                        }
                        else
                        {
                            f.MoveTo(f.FullName.Replace(parent, path));
                        }
                    }
                    Directory.Delete(%%1, true);
                }

 

 

 

移动目录下所有的文件夹到另一个目录下

 

DirectoryInfo d = new DirectoryInfo(%%1);
foreach (DirectoryInfo dirs in d.GetDirectories())
{
    Queue<FileSystemInfo> al = new Queue<FileSystemInfo>(dirs.GetFileSystemInfos());
    while (al.Count > 0)
    {
        FileSystemInfo temp = al.Dequeue();
        FileInfo file = temp as FileInfo;
        if (file == null)
        {
            DirectoryInfo directory = temp as DirectoryInfo;
            Directory.CreateDirectory(path + directory.Name);
            foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())
                al.Enqueue(fsi);
        }
        else
            File.Copy(file.FullName, path + file.Name);
    }
}

 

 

以一个文件夹的框架在另一个目录创建文件夹和空文件

 

bool b=false;
string path = (%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%1 + "\");
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count > 0)
{
    FileSystemInfo tmp = Folders.Dequeue();
    FileInfo f = tmp as FileInfo;
    if (f == null)
    {
        DirectoryInfo d = tmp as DirectoryInfo;
        Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
        foreach (FileSystemInfo fi in d.GetFileSystemInfos())
        {
            Folders.Enqueue(fi);
        }
    }
    else
    {
        if(b) File.Create(f.FullName.Replace(parent, path));
    }
}

 

 

 

 

复制文件

File.Copy(%%1,%%2);

 

 

 

复制一个文件夹下所有的文件到另一个目录

foreach (string fileStr in Directory.GetFiles(%%1))
 File.Copy((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + "\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\"+Path.GetFileName(fileStr));

 

提取扩展名

string %%2=Path.GetExtension(%%1);

提取文件名

string %%2=Path.GetFileName(%%1);

 

替换扩展名

File.ChangeExtension(%%1,%%2);

提取文件路径

string %%2=Path.GetDirectoryName(%%1);

 

 

 

 

 

 

 

 

 

 

上传文件:

ajax接口

 //上传文件,以视频为例
            upload.render({
                elem: '#btnVideo',
                url: 'Upload',
                data: { "type": "media" },
                accept: 'video', //视频
                acceptMime: 'video/*',
                before: function () {
                    index = layer.load();
                },
                done: function (res) {
                    layer.close(index);
                    //do something()
                }
            });

 

 接口:

  public JsonResult UploadVideo()
        {
            string rename = Request["name"];
            var result = new Dictionary<string, object>();
            result["code"] = -1;
            Dictionary<string, object> data = new Dictionary<string, object>();
           
            string fileName = string.Empty;
            try
            {
               
                string t = Request["t"];//类型,img,表示图片类的,file表示文件类
                string selfPath = Request["p"];//自定义文件夹名称
                var file = Request.Files[0]; //获取选中文件  
                Stream stream = file.InputStream;    //将文件转为流 
                string ext = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                int size = file.ContentLength/1024;
                if (size > 102400)
                {
                    result["code"] = -1;
                    result["msg"] = "视频大于100M,请重新选择";
                }
                else {
                    //文件保存位置及命名,精确到毫秒并附带一组随机数,防止文件重名,数据库保存路径为此变量  
                    string dir = "/Upload/Temporary/";
                    string rootPath = Server.MapPath(dir);
                    if (!Directory.Exists(rootPath))
                        Directory.CreateDirectory(rootPath);
                    Random ran = new Random((int)DateTime.Now.Ticks);//利用时间种子解决伪随机数短时间重复问题  
                    if (string.IsNullOrWhiteSpace(rename))
                    {
                        fileName = DateTime.Now.ToString("mmssms") + ran.Next(99999);
                    }
                    else
                    {
                        fileName = rename;
                    }

                    string serverPath = dir + fileName + ext;
                    //路径映射为绝对路径  
                    string path = Server.MapPath(serverPath);
                    if (t == "img")
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);//将流中的图片转换为Image图片对象  
                        img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);//图片保存,JPEG格式图片较小  
                        result["data"] = serverPath;
                        result["code"] = 0;
                    }
                    else
                    {
                        file.SaveAs(path);
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);

                        data.Add("src", serverPath);
                        data.Add("title", fileName);
                       
                        data.Add("ImgSeal", imgpath);
                        result["data"] = data;
                        result["code"] = 0;
                    }
                }
                
            }
            catch (Exception ex)
            {
                result["code"] = -1;
                LogerHelper.Error(ex);
            }
            return Json(result, JsonRequestBehavior.AllowGet);
    }

参考博客

https://www.cnblogs.com/zengxh/p/12390516.html

https://blog.csdn.net/qq_41209575/article/details/89178020

https://www.cnblogs.com/shenchao/p/5128218.html

http://c.biancheng.net/csharp/100/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值