C#二进制转下载上传文件,删除文件源码及调用操作

6 篇文章 0 订阅

1、二进制转文件操作。

首先调用

//你的文件
byte[] data = null;
//路径
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + @"\\Uploads\\";
string errMsg = string.Empty;
string guid = Guid.NewGuid().ToString();
UploadFile(data, filePath, guid + ".xml", ref errMsg);

函数实现

        /// <summary>
        /// 文件
        /// </summary>
        /// <param name="fs">二进制流</param>
        /// <param name="vitualPath">路径</param>
        /// <param name="fileName">文件名</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        private bool UploadFile(byte[] fs, string vitualPath, string fileName, ref string msg)
        {
            string filepath;
            if (!System.IO.Directory.Exists(vitualPath))
            {
                System.IO.Directory.CreateDirectory(vitualPath);
            }
            if (vitualPath.EndsWith("\\"))
            {
                filepath = vitualPath + fileName;
            }
            else
                filepath = vitualPath + "\\" + fileName;
            try
            {
                ///定义并实例化一个内存流,以存放提交上来的字节数组。   
                System.IO.MemoryStream m = new System.IO.MemoryStream(fs);
                ///定义实际文件对象,保存上载的文件。   
                //FileStream f = new FileStream(Server.MapPath("./") + "\\"
                //  + FileName, FileMode.Create);

                System.IO.FileStream f = new System.IO.FileStream(filepath, System.IO.FileMode.Create);

                ///把内内存里的数据写入物理文件   
                m.WriteTo(f);
                m.Close();
                f.Close();
                f = null;
                m = null;
                msg = "";
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }

2、删除文件操作。

首先调用

//文件夹路径及名字
DeleteFile(filePath + "/" + guid + ".txt");

函数实现

        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="filePath"></param>
        private void DeleteFile(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    System.IO.File.Delete(filePath);
                }
                catch
                { }
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值