遇到一个奇怪的问题,C#读取mysql中文正常,写入时发生乱码 网上查阅原因,发现如下信息 ——————————————————————— 一、错误读出 现象:一个已经存在数据的MySQL数据库,该数据库的数据用系统中其它软件、网页查看均正常,使用MySQLcc之类的客户端查看也正常,可是在新写的网页中总是显示乱码。 分析:其它系统都可以正常查看数据,说明数据本身是没有问题的。在网页中显示乱码,一定是网页的编码字符集和获取到的数据的编码字符集不一至。比如数据库的字符集是UTF8的,而网页的字符集是gb2312的,那么网页就会把UTF8编码的字体串当作gb2312的来处理,结果产生乱码。 解决办法:在连接数据库时,设定连接字符集,使连接字符集和当前网页或客户端程序使用的字符集一致。可以使用MySQL的Set Names指令设定连接字符集。假设网页的字体集为gb2312。在连接MySQL后,在连接上执行如下SQL语句: Set Names ‘gb2312’ 在以后所有这个连接上的查询,MySQL都会自动把数据库中的数据转换成gb2312编码格式传过来。 二、错误写入 现象:一个网页或程序向一个MySQL数据库中写数据,写完后,这个网页或程序自己可以正常读取数据,而从其它客户端或网页中读取数据都是乱码。 分析:其它的正常的客户端出现乱码,说明数据库中的字符编码不对。写数据的那个网页能正常读取,是因为写和读都用了错误的编码格式,将错就错,反而能读出正确的数据了。比如数据库中设定的字符集为UTF8,而网页使用gb2312编码执行了插入数据的SQL,那么MySQL就会把这些gb2312的编码当成是UTF8的编码写进数据库。当其它客户端访问数据时,会按系统的设定,以UTF8 格式读取数据,而数据其实是使用gb2312编码的,结果就出现了乱码。只有写数据的那个网页会把这些数据当成gb2312的,也只有那个网页能正常显示数据。 解决办法:同第一条,即:使用Set Names指令设定连接字符集。 在设定了连接字符体的连接上执行数据操作,所有的数据都将被MySQL自动、正确地转换为数据库中设定的编码格式保存。 通过以上两点,我们可以看到,只要在连接MySQL时,正确地设定了字符集,无论数据库本身是使用什么格式编码的,都能得到正确的结果。也许有人会以为写数据时设定的字符集必需和读数据时一致,事实上完全没有必要。程序所要做的只是告诉 MySQL,目前操作MySQL使用的是什么字符集即可。因为MySQL会自动完成如下的转换工作: 写数据库时用的字符集-->存诸数据的字符集-->读取数据的字符集。 笔者以为MySQL对多语言字符集的处理是非常优秀的,并且每次建立到MySQL的连接都会立刻使用Set Names设定字符集,然而最近还是出现了一回乱码,如下面所述。 三、无知的程序包 现象:使用C#编程,使用MySQL提供的连接程序库包访问数据库,使用 MySqlConnection类连接数据库,连接之后立刻调用Set Names设定连接字符串,然后使用MySqlCommand类执行SQL,并使用MySqlDataReader读取数查询结果。然而,当我调用 MySqlDataReader的成员方法GetString获取数据的时候,发现得到的全是乱码。百思不得其解。 分析:经仔细检查,确信问题没有出在MySQL连接上面,这时我想到了C#中对 string类型的处理。在C#中字符串和C/C++中有很大不同。在C/C++中一个字符就是一个字节,而在C#中,按不同的编码格式,一个字符也可以是多个字节的。比如”啊”就是一个字符,如果一个字符串s=”啊”; 那么s的Length属性为1,而不是C/C++中的2。我想MySQL程序包也许并不知道连接上传过来的字符是什么编码的,它因为无知,所以只是按单字节字符把这些数据组织成一个string,这个生成的string就是我得到的乱码。事实上也的确是这样。 解决办法:把这些数据重新组织起来,然后使用正确的编码方法重新生成string。C#中System.Text包内的Encoding类提供了字符集的编/解码方法。 1)首先还是设定连接字符集,以确认收到的字符的编码方式。 2)把GetString得到的字符串转换到byte数组中。 3)使用Systec.Text.Encoding包中相应字符集的解码方法GetString得到新的字符串。 为了通用性,我们使用System.Text.Encoding的默认字符集。连接数据库时,设置数据库连接字符集使用的SQL指令strSetCharset为如下值: string strSetCharset = “Set Names ” + System. Text. Encoding .Default. HeaderName; 在获取数据时,使用下面的函数得到真正的字符串: private string DBStringToNormal(string dbStr) { byte[] str = new byte[dbStr.Length]; for (int i = 0; i < dbStr.Length; ++i) str[i] = (byte)(dbStr[i]); return System.Text.Encoding.Default.GetString(str, 0, […]
View DetailsDataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件。它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特性。 关于本文档: 本文档不准备面面俱到地介绍DataGridView,而是着眼于深入地介绍一些技术点的高级特性。 本文档按逻辑分为5个章节,首先是结构和特性的概览,其次是内置的列/单元格类型的介绍,再次是数据操作相关的内容,然后是主要特性的综述,最后是最佳实践。 大部分章节含有一个“Q & A”部分,来回答该章节相关的一些常见问题。注意,某些问题会由于知识点的关联性重复出现在多个章节。这些问题、答案及其附带的示例代码都包含在本文档的附录部分。 内容 1 何为DataGridView.. 4 1.1 DataGridView和DataGrid 之间的区别… 4 1.2 DataGridView的亮点… 5 2 DataGridView的结构… 6 2.1 结构元素… 6 2.2 单元格和组… 6 2.3 DataGridView的单元格… 6 2.3.1 DataGridViewCell的工作机制… 7 2.4 DataGridView的列… 9 2.5 DataGridView的编辑控件… 9 2.6 DataGridView的行… 10 3 列/单元格类型揭密… 11 3.1 DataGridViewTextBoxColumn. 11 3.2 DataGridViewCheckBoxColumn. 12 3.3 DataGridViewImageColumn. 12 3.4 DataGridViewButtonColumn. 13 3.5 DataGridViewComboBoxColumn. 13 3.5.1 DataError与ComboBox列… 13 3.6 DataGridViewLinkColumn. 14 4 操作数据… 15 4.1 数据输入和验证的相关事件… 15 4.1.1 数据验证相关事件的顺序… 15 4.1.2 验证数据… 15 4.1.3 在新行中的数据输入… 16 4.2 关于Null值… 19 4.2.1 […]
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; using System.Data.Common; using System.Web.Script.Serialization; using System.Globalization; using System.Collections; using System.IO; using System.Drawing; using System.IO.Compression; using System.Runtime.Serialization.Formatters.Binary; namespace Pub.Class { public static class ArrayExtensions { public static bool IsNullEmpty(this Array array) { return array == null || array.Length == 0; } public static bool IsNullEmpty(this ArrayList list) { return (list == null) || (list.Count == 0); } public static int GetInArrayID(this string[] stringArray, string strSearch, bool caseInsensetive) { for (int i = 0; i < stringArray.Length; i++) { if (caseInsensetive) { if(strSearch.ToLower() == stringArray[i].ToLower()) return i; } else { if(strSearch == stringArray[i]) return i; } } return -1; } public static int GetInArrayID(this string[] stringArray, string strSearch) { return GetInArrayID(stringArray, strSearch, true); } public static string ToDelimitedString<T>(this T[] array, string format, string delimiter) { if (array == null || array.Length == 0) return string.Empty; if (format.IsNullEmpty()) format = "{0}"; StringBuilder builder = new StringBuilder(); for (int index = 0; index < array.Length; ++index) { if (index != 0) builder.Append(delimiter); builder.AppendFormat(format, array[index]); } return builder.ToString(); } public static T[] RemoveDuplicates<T>(this T[] array) { ArrayList al = new ArrayList(); for (int i = 0; i < array.Length; i++) { if (!al.Contains(array[i])) al.Add(array[i]); } return (T[])al.ToArray(typeof(T)); } public static T[] Slice<T>(this T[] array, int start, int end) { if (start >= array.Length) { start = 0; end = 0; } if (end < 0) end = array.Length - start - end; if (end <= start) end = start; if (end >= array.Length) end = array.Length-1; int len = end - start + 1; T[] res = new T[len]; for (int i = 0; i < len; i++) res[i] = array[i + start]; return res; } public static string Join<T>(this T[] array, string splitStr) { StringBuilder sb = new StringBuilder(); foreach(T info in array) { sb.AppendFormat("{0}{1}", info.ToString(), splitStr); } return sb.ToString().Left(sb.Length - splitStr.Length); } public static void Action<T>(this T[] inArray, Action<T, Int32> inAction) { for (int i0 = 0; i0 < inArray.GetLength(0); i0++) { inAction(inArray[i0], i0); } } public static void Action<T>(this T[,] inArray, Action<T, Int32, Int32> inAction) { for (int i0 = 0; i0 < inArray.GetLength(0); i0++) { for (int i1 = 0; i1 < inArray.GetLength(1); i1++) inAction(inArray[i0, i1], i0, i1); } } public static void Action<T>(this T[,,] inArray, Action<T, Int32, Int32, Int32> inAction) { for (int i0 = 0; i0 < inArray.GetLength(0); i0++) { for (int i1 = 0; i1 < inArray.GetLength(1); i1++) { for (int i2 = 0; i2 < inArray.GetLength(2); i2++) inAction(inArray[i0, i1, i2], i0, i1, i2); } } } public static void Action<T>(this T[,] inArray, Int32 inDimension, Int32 inIndex, Action<T, Int32> inAction) { if (inDimension == 0) { for (int i = 0; i < inArray.GetLength(1); i++) inAction(inArray[inIndex, i], i); } else if (inDimension == 1) { for (int i = 0; i < inArray.GetLength(0); i++) inAction(inArray[i, inIndex], i); } else { throw new ArgumentException("inDimension must be zero or one"); } } public static void Action<T>(this T[,,] inArray, Int32 inDimension, Int32 inIndex, Action<T, Int32, Int32> inAction) { if (inDimension == 0) { for (int i0 = 0; i0 < inArray.GetLength(1); i0++) { for (int i1 = 0; i1 < inArray.GetLength(2); i1++) inAction(inArray[inIndex, i0, i1], i0, i1); } } else if (inDimension == 1) { for (int i0 = 0; i0 < inArray.GetLength(0); i0++){ for (int i1 = 0; i1 < inArray.GetLength(2); i1++) inAction(inArray[i0, inIndex, i1], i0, i1); } } else if (inDimension == 2) { for (int i0 = 0; i0 < inArray.GetLength(0); i0++){ for (int i1 = 0; i1 < inArray.GetLength(1); i1++) inAction(inArray[i0, i1, inIndex], i0, i1); } } else { throw new ArgumentException("inDimension must be zero or one or two"); } } public static Image ToImage(this byte[] bytes) { if (bytes != null) { MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); ms.Write(bytes, 0, bytes.Length); return Image.FromStream(ms, true); } return null; } public static bool ToFile(this byte[] bytes, string fileName, FileMode fileMode) { bool returnValue = true; FileAccess fileAccess = FileAccess.ReadWrite; if (fileMode == FileMode.Append) fileAccess = FileAccess.Write; FileStream fs = new FileStream(fileName, fileMode, fileAccess); BinaryWriter bw = new BinaryWriter(fs); try { bw.Write(bytes); } catch (Exception) { returnValue = false; } finally { fs.Close(); bw.Close(); } return returnValue; } public static byte[] Compress(this byte[] data) { using (MemoryStream output = new MemoryStream()) { using (DeflateStream def = new DeflateStream(output, CompressionMode.Compress)) { def.Write(data, 0, data.Length); } return output.ToArray(); } } public static byte[] Decompress(this byte[] data) { using (MemoryStream input = new MemoryStream()) { input.Write(data, 0, data.Length); input.Position = 0; using (DeflateStream def = new DeflateStream(input, CompressionMode.Decompress)) { using (MemoryStream output = new MemoryStream()) { byte[] buff = new byte[64]; int read = -1; read = def.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, read); read = def.Read(buff, 0, buff.Length); } def.Close(); return output.ToArray(); } } } } public static T Decompress<T>(this byte[] compressedData) where T : class { return compressedData.Decompress().Deserialize<T>(); } public static T Deserialize<T>(this byte[] data) where T : class { var formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream(data)) return formatter.Deserialize(ms) as T; } public static bool IsInArray(this string[] stringArray, string strSearch, bool caseInsensetive) { return stringArray.GetInArrayID(strSearch, caseInsensetive) >= 0; } public static bool IsInArray(this string[] stringarray, string str) { return stringarray.IsInArray(str, false); } public static bool IsInIPArray(this string[] iparray, string ip) { string[] userip = ip.Split(@"."); for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++) { string[] tmpip = iparray[ipIndex].Split(@"."); int r = 0; for (int i = 0; i < tmpip.Length; i++) { if (tmpip[i] == "*") return true; if (userip.Length > i) { if (tmpip[i] == userip[i]) r ++; else break; } else break; } if (r == 4) return true; } return false; } //Action<string, int> MsgW3 = (s, i) => { Msg.Write(s + i); Msg.Write("<br />"); }; //"test1,test2,test3".Split(',').Action<string>(MsgW3); } } |
转自:http://www.cnblogs.com/livexy/archive/2010/07/06/1772502.html
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/// <summary> /// 生成缩略图 /// </summary> /// <param name="imgPath">源图片路径</param> /// <param name="thumbnailPath">缩略图保存路径</param> /// <param name="newWidth">新宽度</param> /// <param name="newHeight">新高度</param> /// <param name="addSpace">是否添加空白</param> /// <returns></returns> public static void Thumbnail(string imgPath, string thumbnailPath, int newWidth, int newHeight, bool addSpace) { int sW, sH; // 按比例缩放 var imgSource = Image.FromFile(imgPath); var sWidth = imgSource.Width; var sHeight = imgSource.Height; if (sHeight > newHeight || sWidth > newWidth) { if ((sWidth * newHeight) > (sHeight * newWidth)) { sW = newWidth; sH = (newWidth * sHeight) / sWidth; } else { sH = newHeight; sW = (sWidth * newHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } var outBmp = addSpace ? new Bitmap(newWidth, newHeight) : new Bitmap(sW, sH); var x = 0; var y = 0; if (addSpace) { var whRate = newWidth > newHeight ? true : false; //宽是否大于高(新尺寸) x = whRate ? (newWidth - sW) / 2 : x; y = whRate ? (newHeight - sH) / 2 : y; } var g = Graphics.FromImage(outBmp); // 设置画布的描绘质量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle(x, y, sW, sH), new Rectangle(0, 0, imgSource.Width, imgSource.Height), GraphicsUnit.Pixel); g.Dispose(); try { //保存图片 outBmp.Save(thumbnailPath, ImageFormat.Jpeg); } finally { imgSource.Dispose(); g.Dispose(); outBmp.Dispose(); } } |
FlashPaper是一个虚拟打印机,可将word文件转化成swf格式文件(.doc .xls .txt .pdf等文件都可以正常生成SWF格式)。最近简单学习了在ASP.NET页面中调用FlashPaper将word文件转化成swf格式文件的方法。 (1)安装FlashPape:下载FlashPape压缩包,解压缩后,运行初始化目录中的初始化.bat,然后安装FlashPaperDriverInstall2.exe,即FlashPaper打印机。特别注意,在有的机器上要更改Macromedia FlashPape的端口,应为FlashPape2PrinterPort,如果是LPT1这个端口,当然打印不出来了。 (2)为页面中的按钮编写事件处理代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
Process process = new Process(); //创建进程对象 //try //{ ProcessStartInfo startInfo = new ProcessStartInfo(); string paperroot = @"C:\Program Files\Macromedia\FlashPaper 2\FlashPrinter.exe"; string docFile = Server.MapPath("1.doc"); string swfFile = Server.MapPath("1.swf"); startInfo.FileName = paperroot; startInfo.Arguments = docFile + " -o " + swfFile; startInfo.UseShellExecute = false; //不使用系统外壳程序启动 startInfo.RedirectStandardInput = false; //不重定向输入 startInfo.RedirectStandardOutput = false; //重定向输出 startInfo.CreateNoWindow = true; //不创建窗口 process.StartInfo = startInfo; process.Start(); Response.Write("已经提交生成。<br />"); Response.Write(paperroot+"<br />"+docFile + " = " + swfFile); //} //catch (Exception ex) //{ // Response.Write(ex.Message); //} //finally //{ if (process != null) process.Close(); // Response.Write("<br />finally"); //} |
示例代码3:
1 |
public static void TransformFile(string filepath) |
{ string fppath = System.Configuration.ConfigurationManager.AppSettings["Flashpaper"]; string outpath = filepath.Substring(0, filepath.LastIndexOf('.')) + ".swf"; string param = fppath + " " + filepath + " -o " + outpath; Process p = new Process(); p.StartInfo.FileName = "C:\\WINDOWS\\system32\\cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; //p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; try { p.Start(); string strOutput = null; p.StandardInput.WriteLine(param); p.StandardInput.WriteLine("exit"); strOutput = p.StandardOutput.ReadToEnd(); Console.WriteLine(strOutput); p.WaitForExit(); p.Close(); } catch (Exception ex) { throw ex; } }
View Details就象大家更熟悉的const一样,volatile是一个类型修饰符(type specifier)。它是被设计用来修饰被不同线程访问和修改的变量。如果没有volatile,基本上会导致这样的结果:要么无法编写多线程程序,要么编译器失去大量优化的机会。
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class StrBinConvertor { /// <summary> /// 将 字符串 转成 二进制 “10011100000000011100011111111101” /// </summary> /// <param name="s"></param> /// <returns></returns> public static string StrToBin(string s) { var data = Encoding.Unicode.GetBytes(s); var result = new StringBuilder(data.Length * 8); foreach (var b in data) { result.Append(Convert.ToString(b, 2).PadLeft(8, '0')); } return result.ToString(); } /// <summary> /// 将二进制 “10011100000000011100011111111101” 转成 字符串 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string BinToStr(string s) { var cs = System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures; var data = new byte[cs.Count]; for (var i = 0; i < cs.Count; i++) { data[i] = Convert.ToByte(cs[i].Value, 2); } return Encoding.Unicode.GetString(data, 0, data.Length); } } |
HttpWebRequest 是 .net 基类库中的一个类,在命名空间 System.Net 下面,用来使用户通过 HTTP 协议和服务器交互。 HttpWebRequest 对 HTTP 协议进行了完整的封装,对 HTTP 协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。 程序使用 HTTP 协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成,下面对这两种方式进行一下说明: 1. GET 方式。 GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。程序代码如下: HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/webhp?hl=zh-CN" );req.Method = "GET";using (WebResponse wr = req.GetResponse()){ //在这里对接收到的页面内容进行处理} 2. POST 方式。 POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。程序代码如下: string param = "hl=zh-CN&newwindow=1";byte[] bs = Encoding.ASCII.GetBytes(param); HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/intl/zh-CN/" );req.Method = "POST";req.ContentType = "application/x-www-form-urlencoded";req.ContentLength = bs.Length; using (Stream reqStream = req.GetRequestStream()){ reqStream.Write(bs, 0, bs.Length);}using (WebResponse wr = req.GetResponse()){ //在这里对接收到的页面内容进行处理} 在上面的代码中,我们访问了 www.google.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。 3. 使用 GET 方式提交中文数据。 GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312 方式编码访问的程序代码如下: Encoding myEncoding = Encoding.GetEncoding("gb2312");string address = "http://www.baidu.com/s?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);req.Method = "GET";using (WebResponse wr = req.GetResponse()){ //在这里对接收到的页面内容进行处理} 在上面的程序代码中,我们以 GET 方式访问了网址 http://www.baidu.com/s ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。常见的网站中, www.baidu.com (百度)的编码方式是 gb2312, www.google.com (谷歌)的编码方式是 utf8。 4. 使用 POST 方式提交中文数据。 POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。用 gb2312 方式编码访问的程序代码如下: Encoding myEncoding = Encoding.GetEncoding("gb2312");string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding); byte[] postBytes = Encoding.ASCII.GetBytes(param); HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" );req.Method = "POST";req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";req.ContentLength = postBytes.Length; using (Stream reqStream = req.GetRequestStream()){ reqStream.Write(bs, 0, bs.Length);}using (WebResponse wr = req.GetResponse()){ //在这里对接收到的页面内容进行处理} 从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。 以上列出了客户端程序使用 HTTP 协议与服务器交互的情况,常用的是 GET 和 POST 方式。现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。 转自:http://www.cnblogs.com/webman/archive/2006/11/17/564106.html
View Details1、用MySQLDriverCS连接MySQL数据库 先下载和安装MySQLDriverCS,地址: http://sourceforge.net/projects/mysqldrivercs/ 在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中 注:我下载的是版本是 MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Odbc; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySQLDriverCS; namespace mysql { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { MySQLConnection conn = null; conn = new MySQLConnection(new MySQLConnectionString(“localhost”, ”inv”, ”root”, ”831025″).AsString); conn.Open(); MySQLCommand commn = new MySQLCommand(“set names gb2312″, conn); commn.ExecuteNonQuery(); string sql = ”select * from exchange “; MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn); DataSet ds = new DataSet(); mda.Fill(ds, ”table1″); this.dataGrid1.DataSource = ds.Tables["table1"]; conn.Close(); } } } 2、通过ODBC访问mysql数据库: 参考:http://www.microsoft.com/china/community/Column/63.mspx 1. 安装Microsoft ODBC.net:我安装的是mysql-connector-odbc-3.51.22-win32.msi 2. 安装MDAC 2.7或者更高版本:我安装的是mdac_typ.exe 2.7简体中文版 3. 安装MySQL的ODBC驱动程序:我安装的是 odbc_net.msi 4. 管理工具 -> 数据源ODBC –>配置DSN… 5. 解决方案管理中添加引用 Microsoft.Data.Odbc.dll(1.0.3300) 6. 代码中增加引用 using Microsoft.Data.Odbc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; //vs2005好像没有这个命名空间,在c#2008下测试自动生成的 using System.Text; using System.Windows.Forms; using Microsoft.Data.Odbc; namespace mysql { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string MyConString = ”DRIVER={MySQL ODBC 3.51 Driver};” + ”SERVER=localhost;” + ”DATABASE=inv;” + ”UID=root;” + ”PASSWORD=831025;” + ”OPTION=3″; OdbcConnection MyConnection = new OdbcConnection(MyConString); MyConnection.Open(); Console.WriteLine(“”n success, connected successfully !”n”); string query = ”insert into test values( ‘hello’, ‘lucas’, ‘liu’)”; OdbcCommand cmd = new OdbcCommand(query, MyConnection); //处理异常:插入重复记录有异常 try{ cmd.ExecuteNonQuery(); } catch(Exception ex){ Console.WriteLine(“record duplicate.”); }finally{ […]
View Details计算机在最初只支持ASCII编码,但是后来为了支持其他语言中的字符(比如汉字)以及一些特殊字符(比如€),就引入了Unicode字符集。基于Unicode字符集的编码方式有很多,比如UTF-7、UTF-8、Unicode以及UTF-32。在Windows操作系统中,一个文本文件的前几个字节是用来指定该文件的编码方式的。如果你使用NotePad或WordPad来打开一个文本文件,你并不用担心该文件的编码方式,因为这些应用程序会先读取文件的前几个字节来确定该文件的编码方式,然后用正确的编码将文本中的每个字符显示出来。下面的图中,可以看到当用NotePad记事本保存一个文档时,可以选择的编码(Encoding)方式有哪些。 用.Net读取文本文件或写入文本文件,你都不须要担心编码方式。.Net已经将这些封装好了。在读取一个文本文件的时候,如果你已经知道文本使用的是什么编码方式,你可以指定使用哪种编码方式读取文本,否则如果不指定编码方式,.Net会读取文本的前几个字节来确定使用哪种编码方式读取文件内容的。在写入文本文件的时候,你也可以指定你想使用的编码方式。如果你没有指定编码,.Net会根据写入的文本是否含有特殊字符来决定编码方式。如果没有特殊字符,就采用ASCII编码,如果有特殊字符,就采用UTF-8编码。 (一) 读取文件 如果你要读取的文件内容不是很多,可以使用 File.ReadAllText(FilePath) 或指定编码方式 File.ReadAllText(FilePath, Encoding)的方法。它们都一次将文本内容全部读完,并返回一个包含全部文本内容的字符串 string str = File.ReadAllText(@"c:\temp\ascii.txt"); // 也可以指定编码方式 string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII); 也可以使用方法File.ReadAllLines。该方法返回一个字符串数组。每一行都是一个数组元素。 string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt"); // 也可以指定编码方式 string[] strs2 = File.ReadAllLines(@"c:\temp\ascii.txt", Encoding.ASCII); 当文本的内容比较大时,我们就不要将文本内容一次读完,而应该采用流(Stream)的方式来读取内容。.Net为我们封装了StreamReader类。初始化StreamReader类有很多种方式。下面我罗列出几种 StreamReader sr1 = new StreamReader(@"c:\temp\utf-8.txt"); // 同样也可以指定编码方式 StreamReader sr2 = new StreamReader(@"c:\temp\utf-8.txt", Encoding.UTF8); FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr3 = new StreamReader(fs); StreamReader sr4 = new StreamReader(fs, Encoding.UTF8); FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); // OpenText 创建一个UTF-8 编码的StreamReader对象 StreamReader sr5 = myFile.OpenText(); // OpenText 创建一个UTF-8 编码的StreamReader对象 StreamReader sr6 = File.OpenText(@"C:\temp\utf-8.txt"); 初始化完成之后,你可以每次读一行,也可以每次读一个字符 ,还可以每次读几个字符,甚至也可以一次将所有内容读完。 // 读一行 string nextLine = sr.ReadLine(); // 读一个字符 int nextChar = sr.Read(); // 读100个字符 int nChars = 100; char[] charArray = new char[nChars]; int nCharsRead = sr.Read(charArray, 0, nChars); // 全部读完 string restOfStream = sr.ReadToEnd(); 使用完StreamReader之后,不要忘记关闭它: sr.Closee(); 假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子: StreamReader sr = File.OpenText(@"C:\temp\ascii.txt"); string nextLine; while ((nextLine = sr.ReadLine()) != null) { Console.WriteLine(nextLine); } sr.Close(); (二) 写入文件 写文件和读文件一样,如果你要写入的内容不是很多,可以使用File.WriteAllText方法来一次将内容全部写如文件。如果你要将一个字符串的内容写入文件,可以用File.WriteAllText(FilePath) 或指定编码方式 File.WriteAllText(FilePath, Encoding)方法。 string str1 = "Good Morning!"; File.WriteAllText(@"c:\temp\test\ascii.txt", str1); // 也可以指定编码方式 File.WriteAllText(@"c:\temp\test\ascii-2.txt", str1, Encoding.ASCII); 如果你有一个字符串数组,你要将每个字符串元素都写入文件中,可以用File.WriteAllLines方法: string[] strs = { "Good Morning!", "Good Afternoon!" }; File.WriteAllLines(@"c:\temp\ascii.txt", strs); File.WriteAllLines(@"c:\temp\ascii-2.txt", strs, Encoding.ASCII); 使用File.WriteAllText或File.WriteAllLines方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件。 当要写入的内容比较多时,同样也要使用流(Stream)的方式写入。.Net封装的类是StreamWriter。初始化StreamWriter类同样有很多方式: // 如果文件不存在,创建文件; 如果存在,覆盖文件 StreamWriter sw1 = new StreamWriter(@"c:\temp\utf-8.txt"); // 也可以指定编码方式 // true 是 append text, false 为覆盖原文件 StreamWriter sw2 = new StreamWriter(@"c:\temp\utf-8.txt", true, Encoding.UTF8); // FileMode.CreateNew: 如果文件不存在,创建文件;如果文件已经存在,抛出异常 FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read); // UTF-8 为默认编码 StreamWriter sw3 = new StreamWriter(fs); StreamWriter sw4 = new StreamWriter(fs, Encoding.UTF8); // 如果文件不存在,创建文件; 如果存在,覆盖文件 FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); StreamWriter sw5 = myFile.CreateText(); 初始化完成后,可以用StreamWriter对象一次写入一行,一个字符,一个字符数组,甚至一个字符数组的一部分。 // 写一个字符 sw.Write('a'); // 写一个字符数组 char[] charArray = new char[100]; // initialize these characters sw.Write(charArray); // 写一个字符数组的一部分 sw.Write(charArray, 10, 15); 同样,StreamWriter对象使用完后,不要忘记关闭。sw.Close(); 最后来看一个完整的使用StreamWriter一次写入一行的例子: FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); StreamWriter sw = myFile.CreateText(); string[] strs = { "早上好", "下午好" }; foreach (var s in strs) { sw.WriteLine(s); } sw.Close(); 转自:http://www.cnblogs.com/jfzhu/archive/2012/11/16/2772576.html
View Details