后端常用功能的收集汇总——不定期更新

1、写入文件(c#)

      //字符串数组用System.IO.File.WriteAllLine比较好
     //路径和文件名、字符串数组名字、最后加上Encoding.Default,防止编码问题
     string[] a=new string[3]{"111","222","333"};
     File.WriteAllLines("E:\\try.txt",a,Encoding.Default);

     //字符串用System.IO.File.WriteAllText比较好
     //路径和文件名、字符串名字、最后加上Encoding.Default,防止编码问题
     string b = "444";
     File.WriteAllText("E:\\try.txt", b, Encoding.Default);

     Console.WriteLine("over");
     Console.ReadKey();

 2、复制文件(c#)

       /// <summary>
       /// 复制文件夹及文件
      /// </summary>
        /// <param name="sourceFolder">原文件路径</param>
        /// <param name="destFolder">目标文件路径</param>
        /// <returns></returns>
        public int CopyFolder(string sourceFolder, string destFolder)
        {
            try
            {
                //如果目标路径不存在,则创建目标路径
                if (!System.IO.Directory.Exists(destFolder))
                {
                    System.IO.Directory.CreateDirectory(destFolder);
                }
                //得到原文件根目录下的所有文件
                string[] files = System.IO.Directory.GetFiles(sourceFolder);
                foreach (string file in files)
                {
                    string name = System.IO.Path.GetFileName(file);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    System.IO.File.Copy(file, dest);//复制文件
                }
                //得到原文件根目录下的所有文件夹
                string[] folders = System.IO.Directory.GetDirectories(sourceFolder);
                foreach (string folder in folders)
                {
                    string name = System.IO.Path.GetFileName(folder);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    CopyFolder(folder, dest);//构建目标路径,递归复制文件
                }
                return 1;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return 0;
            }

        }

3、word转pdf(c#)

public bool WordToPDF(string sourcePath, string targetPath)
        {
           bool result = false;
           Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
           Document document = null;
           try
           {
              application.Visible = false;
              document = application.Documents.Open(sourcePath);
              document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
              result = true;
           }
           catch (Exception e)
           {
              Console.WriteLine(e.Message);
              result = false;
           }
           finally
           {
              document.Close();
           }
           return result;
        }

4、不能写入非法字符

function processSpelChar(){
    var code;
    var character;
    if(document.all){
        code = window.event.keyCode;
    }else{
        code = arguments.callee.caller.arguments[0].which;
    }
    var character = String.fromCharCode(code);
    var txt = new RegExp(/["'<>%;)(&+]/);
    if(txt.test(character)){
        if(document.all){
            window.event.returnValue = false;
        }else{
            arguments.callee.caller.arguments[0].preventDefault();
        }
    }
}

5、获取用户IP地址

public static string GetUserIp()
{
      string ip;
      string[] temp;
      bool isErr = false;
      if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
      {
         ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
      }
      else
      {
         ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
      }
      if (ip.Length > 15)
      {
        isErr = true;
      }
      else
      {
        temp = ip.Split('.');
        if (temp.Length == 4)
        {
        for (int i = 0; i < temp.Length; i++)
       {
         if (temp[i].Length > 3) isErr = true;
       }
    }
    else
      isErr = true;
   }
   if(isErr)
   {
     return "1.1.1.1";
   }
   else
  {
    return ip;
  }
}

6、上传文件(前台)

单个文件上传
Html:
<form id="form1">
  <input type="file" name="files" /> 
  <input type="button" value="单文件上传" οnclick="uploadFile()"/>
</form>
Jquery:
在此基础上,需要引用两个js文件:

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

<script src="~/Scripts/jquery.form.js"></script>

function uploadFile() {
$("#form1").ajaxSubmit({
url: "@Url.Action("UploadFile", "Home")",  //这里也可以写成:"/Home/UploadFile",其中Home是Controller的名字;UploadFile是方法名字
type: "post",
success: function (data) {
if (data == "True" || data == true) {
}
else {
}
},
error: function (aa) {
}
});
}
多文件上传
Html:
<form enctype="multipart/form-data" id="form_example">
  <input type="file" id="files" multiple οnchange="addFile()"/><br /><br />
  <input type="button" value="提交" id="submit" οnclick="submitFile()" />
</form>
<div id='file-list-display'></div>
JS:
var fileList = [];

function addFile() {
var files = document.getElementById("files"),
fileListDisplay = document.getElementById('file-list-display');
for (var i = 0; i < files.files.length; i++) {
fileList.push(files.files[i]);
}

fileListDisplay.html = '';
fileList.forEach(function (file, index) {
var fileDisplayEl = document.createElement("p");
fileDisplayEl.innerHTML = (index + 1) + ":" + file.name;
fileListDisplay.appendChild(fileDisplayEl);
})
}

function submitFile() {
var formData = new FormData();
//循环添加到formData中
fileList.forEach(function (file) {
formData.append('files', file, file.name);
})

$.ajax({
url: "/Home/UploadFile",
type: 'POST',
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
async: false,
success: function (data) {
if (data) {
}
}
});
}

6、上传文件(后台)

/// <summary>
        /// 文件上传到本地
        /// </summary>
        public void Upload()
        {
            try
            {
                HttpFileCollection hpFiles = HttpContext.Current.Request.Files;
                for (int i = 0; i < hpFiles.Count; i++)
                {

                    if (hpFiles[i] == null || hpFiles[i].FileName.Trim() == "")
                    {
                        _Error = 1;
                        return;
                    }
                    string Ext = GetExt(hpFiles[i].FileName);
                    //if (!IsUpload(Ext))
                    //{
                    //    _Error = 2;
                    //    return;
                    //}
                    int iLen = hpFiles[i].ContentLength;
                    if (iLen > _MaxSize)
                    {
                        _Error = 3;
                        return;
                    }

                    if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
                    byte[] bData = new byte[iLen];
                    hpFiles[i].InputStream.Read(bData, 0, iLen);
                    string FName;
                    if (_IsChangeName)
                    {
                        FName = NewFileName(Ext);
                    }
                    else
                    {
                        FName = hpFiles[i].FileName;
                    }
                    FileStream newFile = new FileStream(_SavePath + FName, FileMode.OpenOrCreate);
                    newFile.Write(bData, 0, bData.Length);
                    newFile.Flush();
                    int _FileSizeTemp = hpFiles[i].ContentLength;

                    string ImageFilePath = _SavePath + FName;

                    newFile.Close();
                    newFile.Dispose();
                    _FileName = hpFiles[i].FileName;
                    _OutFileName = FName;
                    _FileSize = _FileSizeTemp;
                }
                _Error = 0;
                return;
            }
            catch (Exception ex)
            {
                _Error = 4;
                return;
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值