首页 > 其他 > 详细

文件操作

时间:2019-05-12 22:58:03      阅读:152      评论:0      收藏:0      [点我收藏+]

一、删除文件/文件夹

  当服务器上某些文件太多了,需要删除超过一定时间的文件

技术分享图片
if(Directory.Exists(yourPath))
{
   //获取指定路径下所有文件夹
   string[] folderPaths = Directory.GetDirectories(yourPath);
   foreach(string folderPath in folderPaths)
           Directory.Delete(folderPath, true);
   //获取指定路径下所有文件
   string[] filePaths = Directory.GetFiles(yourPath);
   foreach(string filePath in filePaths)
           File.Delete(filePath);
}
//或者
DirectoryInfo folder = new DirectoryInfo(selectPath);
 txtFilesPath.Text = selectPath;
  foreach (FileInfo file in folder.GetFiles())
   {
//删除超过一定时间的文件
   if ((DateTime.Today - file.CreationTime).TotalDays   > dayCount)
              {
                File.Delete(file.FullName);
               }
View Code

如果你需要连你指定的文件夹一起删除 就简单的多 如下

if(Directory.Exists(yourPath)){

Directory.Delete(yourPath,true);

 }

上述两例中的yourPath应为指定文件夹的路径 如: D:\test 

第一例则会删除test文件夹下的所有子项

第二例则是test文件夹及其子项一起删除 需要注意的是Directory.Delete方法有两个重载 举例说明:

Directory.Delete(yourPath); //如果yourPath有子项 则删除失败 抛出异常

Directory.Delete(yourPath,true); //第二个为bool类型参数 表示是否需要使用递归删除 

补充说明 如果只是需要删除文件 就使用File类 如下

 if(File.Exists(filePath))

File.Delete(filePath) 

上例中的filePath为文件的完整路径 如: C:\test\test.txt

二、获取文件字节流

  远程http(s)文件

HttpWebResponse.ContentLength 报异常:算术运算导致溢出

 技术分享图片

改为:

技术分享图片
using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse())
                {
                    Stream stream = wr.GetResponseStream();
                    //读取到内存
                    MemoryStream stmMemory = new MemoryStream();
                    byte[] buffer1 = new byte[1024 * 100];
                    int i;
                    //将字节逐个放入到Byte 中
                    while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
                    {
                        stmMemory.Write(buffer1, 0, i);
                    }
                    arraryByte = stmMemory.ToArray();
                    stmMemory.Close();
                    stream.Close();
                }
View Code

 

三、web文件上传,webapi后台接收

后台

技术分享图片
 public string Post()
        {
            string key = HttpContext.Current.Request["key"];
            string value = HttpContext.Current.Request["value"];
            HttpFileCollection files = HttpContext.Current.Request.Files;
 
            foreach (string f in files.AllKeys)
            {
                HttpPostedFile file = files[f];
                if (string.IsNullOrEmpty(file.FileName) == false)
                    file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/") + file.FileName);
            }
 
            return key + value;
        }
View Code

前端

技术分享图片
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form name="form" action="http://localhost:31855/api/values" method="post" enctype="multipart/form-data">
        <input type="text" name="key" id="txtKey" />
        <br />
        <input type="text" name="value" id="txtValue" />
        <br />
        <input type="file" name="file" id="upFile" />
        <input type="file" name="file2" id="File1" />
        <br />
        <input type="submit" id="btnSubmit" value="Submit" />
    </form>
</body>
</html>
View Code

 

四、使用FormData对象实现ajax提交表单及文件上传,api处理

1、html代码

技术分享图片
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>文件上传表单ajax提交模拟</title>
</head>
<body>
    <form id="postForm">
        <h2>文件上传表单ajax提交模拟</h2>
        <p>
            ajax提交给后端WebAPI处理,进而交给别人提供的第三方接口处理
        </p>
        <p>文件名:<input type="text" name="filename" /></p>
        <p>  文件: <input type="file" name="my_file" /></p>
        <input type="button" value="提交" onclick="btnPost()" />
    </form>

</body>
</html>
View Code

2、jquery代码:

技术分享图片
 <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
        function btnPost() {
            var formData = new FormData($("#postForm")[0]);
            $.ajax({
                url: "http://localhost/uploadfile/api/UpFile",
                data: formData,
                type: "POST",
                contentType: false,
                processData: false,
                success: function (msg) {
                    alert(msg);  
                },
                error: function (e) {
                }
            });
        }
    </script>
View Code

3、后台webapi处理

技术分享图片
 [HttpPost]
        public  FileUploadResult UploadFile()
        {
            var name = HttpContext.Current.Request.Form["filename"];  //手动填写的文件名
            if (HttpContext.Current.Request.Files.Count <= 0)
            {
                return new FileUploadResult() { ErrorMessage = "沒有文件" };
            }
            var postFile = HttpContext.Current.Request.Files[0];
            var fileName = postFile.FileName; //实际的文件名(含扩展名)
            var ext = Path.GetExtension(fileName).Substring(1);
            fileName = DateTime.Now.ToString("yyyyMMddHHssmmfff") + "." + fileName;

            //Stream转为byte[]
            //byte[] fileBytes = null;
            //using (var ms = new MemoryStream())
            //{
            //    postFile.InputStream.CopyTo(ms);
            //    fileBytes = ms.ToArray();
            //}

            //或者
            byte[] fileBytes = new byte[postFile.InputStream.Length];
            postFile.InputStream.Read(fileBytes, 0, fileBytes.Length);

            var uploadResult = new EditFile().UploadFile(fileName, fileBytes);

            if (uploadResult.success)
            {
                return new FileUploadResult() { success =true,clientUrl=uploadResult.clientUrl };
            }
            else
            {
                return new FileUploadResult() { success = false, clientUrl = uploadResult.ErrorMessage };
            }
        }
View Code

进一步处理代码省略..

技术分享图片
using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse())
                {
                    Stream stream = wr.GetResponseStream();
                    //读取到内存
                    MemoryStream stmMemory = new MemoryStream();
                    byte[] buffer1 = new byte[1024 * 100];
                    int i;
                    //将字节逐个放入到Byte 中
                    while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
                    {
                        stmMemory.Write(buffer1, 0, i);
                    }
                    arraryByte = stmMemory.ToArray();
                    stmMemory.Close();
                    stream.Close();
                }
View Code

 

文件操作

原文:https://www.cnblogs.com/peterYong/p/9599631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!