You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
3.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.IO;
using System.Text;
namespace ZJ_BYD.Untils
{
public class StrHelper
{
///<summary>
///生成随机字符串
///</summary>
///<param name="length">目标字符串的长度</param>
///<param name="useNum">是否包含数字1=包含,默认为包含</param>
///<param name="useLow">是否包含小写字母1=包含,默认为包含</param>
///<param name="useUpp">是否包含大写字母1=包含,默认为包含</param>
///<param name="useSpe">是否包含特殊字符1=包含,默认为不包含</param>
///<param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param>
///<returns>指定长度的随机字符串</returns>
public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
Random r = new Random(BitConverter.ToInt32(b, 0));
string s = null, str = "";
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}
/// <summary>
/// 写入文本文档
/// </summary>
/// <param name="s"></param>
public static bool WriteText(string path, string content)
{
try
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write(content);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
LogHelper.WriteErrorLog("写入文本文件异常", ex);
return false;
}
}
/// <summary>
/// 读取文本文档
/// </summary>
/// <returns></returns>
public static string ReadText(string path)
{
var content = "";
try
{
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var sw = new StreamReader(fileStream, Encoding.Default);
while (!sw.EndOfStream)
{
content = sw.ReadLine();
}
sw.Close();
}
catch (Exception ex)
{
LogHelper.WriteErrorLog("读取文本文件异常", ex);
return null;
}
return content;
}
}
}