C# 里面的编码问题

C#字符编码问题解决方法 C#中遇到乱码问题并不罕见,但是只要注意正确设置源代码文件的编码方式,进行字符编码转换,以及在Web应用程序中进行适当的编码设置,就能轻松解决这类问题。如果你是在C#的Web应用程序中遇到乱码问题,那么可能需要在应用程序的配置文件中进行相应的编码设置。如果你的程序中涉及到字符串的输入、输出或处理,那么就需要考虑字符编码转换的问题。要更改源代码文件的编码方式,可以右键点击文件,选择“属性”选项,然后在“高级”选项卡中更改“编码”属性。方法获取源编码和目标编码的实例,这里源编码为GBK,目标编码为UTF-8。 阅读详情

 

1  .NET中的String只有Unicode一种。所以编码格式的字节序列转换成String时最终都是以Unicode表示。

2 System.Text.Encoding.Default是取系统的当前ANSI代码页的编码,即当前系统的编码。(在我们的机子上一般都是"gb2312")这就每次用Default读取文件流都正确,且必须用Default读取才正确的原因----其实用Encoding.GetEncoding("GB2312")也一样。  

3  String-->byte[](Unicode-->other) 
//string 转成default编码的byte[],编码采用default,我们机器上大部分为gb2312
string a="china中文乱码";
byte[]   abyte   =   System.Text.Encoding.Default.GetBytes(a);   

byte[]-->String(other-->Unicode)
string b = null;
byte[] bbyte = null;
bbyte 
= new byte[100];
PrintStr(abyte,bbyte); 
//得到byte[]
//System.Text.Encoding     ed=   System.Text.Encoding.GetEncoding("GB2312"); 
System.Text.Encoding     ed=  System.Text.Encoding.Default; //编码,和用gb2312一样
b  =   ed.GetString(bbyte); //取得正确编码后的string
StreamReader(string  path, System.Text.Encoding  encoding]),Response.Charset,这就相当于你告诉系统byte[]是什么编码,这时候.NET用你指定的编码方式去解码,然后转换成Unicode编码方式的String.  
也就是说,不管何时,我们所指定的编码都只是指byte[]。  
即Encoding.UTF8.GetString(byte[]   buffer)是告诉系统buffer的编码是UTF8。
byte[]   buf =  Encoding.UTF8.GetBytes(string str)是告诉系统返回的buf编码方式是UTF8。  
字节序是按指定编码方式编码,它有一个特定的编码方式,但它本身是中性的,不含有任何编码信息。   
   

c#字符串编码问题的处理解决 主要介绍了c#字符串编码问题的处理解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 立即下载

相关推荐

IBM 3560M3 R5 坏盘更换记录

公司一台老旧 3650M3在日常巡查过程中发现硬盘报错

ddriv的博客 3953

C# Encoding

之前做公司项目的时候,对于C#编码这块总是一知半解,所以打算通过这篇笔记对C#编码(Encoding)进行彻底的扫盲,关于编码和字符集的基础知识,请参考字符集和字符编码(Charset & Encoding),看完这篇文章之后,来看本文会更加的轻松。 1、Encoding (1)、如何生成一个Encoding即一种编码 Encoding位于System.Text命名空间下,是一个抽象类,它...

weixin_34242819的博客 792

避坑指南:Spring3集成OpenAPI时泛型响应失效的3种解决方案

本文深入探讨了Spring3集成OpenAPI时泛型响应失效的问题,提供了三种实用解决方案:移除@Schema注解、使用@ArraySchema包装泛型以及自定义Schema处理器。针对不同项目规模,详细分析了各方案的适用场景、优缺点及性能影响,帮助开发者高效生成准确的接口文档,提升前后端协作效率。

weixin_30839881的博客 104

C# Encoding.Default.GetByteCount(character)

用于判断字符是全角还是半角。返回的值为bool值。 if(Encoding.Default.GetByteCount(character)){ //character为全角 return true; }else{ //character为半角 return false; }

weixin_46990454的博客 890

MCGS触摸屏数据记录与U盘导出配置全解析

在工业自动化现场,数据记录是设备运行状态分析与故障追溯的基础。HMI触摸屏作为人机交互核心,不仅承担实时监控任务,还负责过程数据的存储与导出。理解数据采集周期、存盘机制与存储介质的匹配原理,能帮助工程师高效配置数据记录功能。合理运用定时存盘、存盘组与U盘导出,可支撑设备趋势分析、报表生成及事故排查。本文以MCGS触摸屏为例,详解数据记录的完整组态流程,并汇总常见配置陷阱与排查思路,为现场调试与长期运维提供可落地的技术参考。

weixin_34253126的博客 477

《UDS协议从入门到精通》系列——图解0x23:通过地址读取内存

如何读取ECU中指定内存地址的数据?图解UDS 0x23服务带你快速上手!!

车载系统攻城狮 2626

c# 字符串函数小结

Compare   比较字符串的内容,考虑文化背景(场所),确定某些字符是否相等   CompareOrdinal  与Compare一样,但不考虑文化背景   Format   格式化包含各种值的字符串和如何格式化每个值的说明符   IndexOf   定位字符串中第一次出现某个给定子字符串或字符的位置   IndexOfAny  定位字符串中第一次出现某个字符或一组字符

Beginner 1352

【WorkBuddy专栏68】HY3绕路部署vsDS4直击根因——一次真实踩坑揭露两个AI模型的推理差距

【WorkBuddy专栏68】HY3绕路部署vsDS4直击根因——一次真实踩坑揭露两个AI模型的推理差距

AI人人懂 573

关于Encoding.GetEncoding("utf-8")和Encoding.GetEncoding("GB2312")及Encoding.Default

<br />最近处理bs的GridView导出word、excel的时候,经常出现乱码的问题,一直很头疼,折腾了两天,从网上了找到了一些资料,其实说到底就是换成byte[]或者字节流最后输入的问题。<br />根据多次在ie6、ie7上测试发现用Encoding.Default的基本可以解决95%的乱码输出的问题,虽然网上有帖子说“谨慎使用Encoding.Default”,原帖见备注一。<br />但是另外的5%的乱码需要Encoding.GetEncoding("utf-8")才能解决,至于Encodi

SpriteNet的专栏 7万+

雨雾天YOLOv8检测拉胯?暗通道去雾+上下文注意力双优化,mAP从58%飙到79%,暴雨也能看清车牌

室外交通监控:高速、省道的雨雾天检测,重点解决小车、货车漏检;车载ADAS系统:雨天行车时的前方车辆、行人识别,需实时性(<40ms);隧道出入口:明暗交界+雾天的复杂场景,暗通道能平衡亮度。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1382

YOLOv5_DeepSORT_Pytorch训练自己的多目标跟踪模型

1 准备 环境配置:https://blog.csdn.net/weixin_50008473/article/details/115250986?spm=1001.2014.3001.5501 YOLOv5_DeepSORT_Pytorch代码地址: https://github.com/mikel-brostrom/Yolov5_DeepSort_Pytorch DeepSORT论文:https://arxiv.org/pdf/1703.07402.pdf 2 训练目标检测模型 训练自己的目标检测模

weixin_50008473的博客 1万+

谨慎使用Encoding.Default

     在处理文本时,经常需要处理Encoding的概念。存在这个问题的原因在于,在.NET程序内文本只是string和char对象,而保存到硬盘时,或者准备用socket把它发送出去时,都得先转换成byte[]或者字节流。而转换的算法,就是Encoding。Encoding不同文本文件的行数也不同。 老外的程序里面,都喜欢用Encoding.ASCII,这是因为他们主要只使用wes...

Corrinejtt 1163

C#上位机+YOLO实时目标检测:摄像头采集+多线程推理+精度调优全流程

标注数据集:使用LabelImg工具标注目标对象,按YOLO格式整理数据集;模型训练:使用Ultralytics库训练自定义模型,提升特定目标的检测精度;训练参数优化:增加训练轮数(epochs=100200)、调整批次大小(batch=1632)、使用数据增强(flip、mosaic等)。摄像头采集:封装通用采集类,支持USB摄像头/网口相机,实现稳定帧读取与异常处理;多线程推理:采用“采集线程+推理线程+UI线程”解耦架构,使用线程安全队列传递帧数据,彻底解决界面卡顿;核心封装。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 680

c# mysql 编码_C#编码问题以及C#往Mysql插数据编码问题

public static string get_uft8(string unicodeString){UTF8Encoding utf8 = new UTF8Encoding();Byte[] encodedBytes = utf8.GetBytes(unicodeString);String decodedString = utf8.GetString(encodedBytes);re...

weixin_29065791的博客 336

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

C# 中 RDotNET 中的编码问题

无论调用abc中的哪一个,设置都不生效,而此时再执行另外两个,设置又生效了,能显示中文了。在Winform应用中,用户输入参数,通过RDotNet调用R的函数进行计算,并返回data.frame。在参数中会传递一组中文名称,这组名称会在返回的data.frame中,当作Column的名称显示。返回的data.frame中有些Column的名称是在函数里自己生成的,目的是为实现中英显示。上面的区组和实验批次是在打包后的R library函数中生成的。在初步解决乱码问题中,已经设置了R的运行环境的语言和编码。

lysh8032的博客 332

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

【C#】网址不进行UrlEncode编码会存在一些问题

欢迎来到《小5讲堂》,大家好,我是全栈小5。 这是2024年第3篇文章,此篇文章是C#知识点实践序列文章,博主能力有限,理解水平有限,若有不对之处望指正!

小5聊的博客 2692

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c# urlencode空格变成+_HttpUtility.UrlEncode()关于空格的编码问题

因为HttpUtility.UrlEncode在Encode的时候,将空格转换成加号"+",在Decode的时候将"+"号转为空格,但是浏览器是不能理解"+"号为空格的,所以如果文件名包含了空格,在浏览器下载得到的文件,空格就变成了"+"号.一个解决办法是,在HttpUtility的UrlEncode之后,将"+" 再手动替换成"%20"(如果原来是"+...

weixin_39613744的博客 2383

C#数据类型转换——方法汇总

string转byte[]: byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str ); byte[]转string: string str = System.Text.Encoding.Default.GetString ( byteArray ); string转ASCII byte[]: byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str ); ASCII

weixin_38713073的博客 1294

Encoding编码

一般使用UTF-8编码(兼容ASCII)。Encoding.Default 指的是系统当前的默认字符编码,容易受平台影响导致不一致。Encoding.编码.GetString(byte[]) byte数组转string(接收时使用)Encoding.编码.GetBytes(string) 将字符串转byte数组(发送时使用)

m0_51684835的博客 592

谈C#中编码Encoding

1.入门C#时经常看到这样的描述:.NET中的String都是Unicode编码。 在入门之后没太看这样的基础书并且多接触一些编码问题后,我的潜意识总觉得String有很多种编码,utf8,unicode,ascii等,并且不认为C#中有gb2312编码。     2.System.Text.Encoding.Default似乎可以解决一切编码,因为我每次用Default.GetString(

wygyhm的专栏 1万+

C# 读取 TXT文件的时候中文乱码解决方法

用C#编写notepad时,读取文件时发现英文显示正常,但是中文就是一个一个方框。如果把txt转换成UTF-8格式时读取就正常,so怀疑是编码问题,仔细查了查帮助,发现Default的说明是“获取系统的当前 ANSI 代码页的编码”,就用了下,果然不是乱码了。所以解决办法就是如下定义StreamReader的对象StreamReader sr = new StreamReader(path,Enco

Denny辉的博客 2万+

C#中文乱码解决:UTF8

https://www.cnblogs.com/mywebname/articles/592337.html XML文件可以采用多种编码,但是经过不同的编码后对于中文会出现乱码问题,比如“骞垮憡涓戦椈”,对于此问题的解决如下: static void Main() { string utf8String = "骞垮憡涓戦椈"; // Create two different encodings. Encoding utf8= E...

深渊的水影 1万+

C#中Encoding简要介绍总结,编码的说明

因为最近写一个作业,要用到网络传输,在网络传输过程中不得不用到Encoding, 需要把要传输的数据编码成字节数组 (byte[] 数组),然后看到有多种编码方式,就对各个方式学习了一下,并给大家共享一下。   在写Web Service的时候,和用Socket传输的时候,我们只能通过byte[] 数组来传送数据,不能返回我们希望的int, long, float等常用类型。这样就会用到Enc

Work Hard, Play Harder! 5817

C#读取文件方法

解决乱码问题 方法一: 需要从streamReader中指定参数即可  StreamReader objReader = new StreamReader(filePath, UnicodeEncoding.GetEncoding("GB2312"));             string sLine = "";                        whi

wczlcj的专栏 586

c#编码问题

文本文件编码,文本文件有不同的存储方式,将字符串以什么样的形式保存为二进制,这个就是编码,UTF-8、ASCII、Unicode等,如 果出现乱码一般就是编码的问题,文本文件相关的函数一般都有一个Encoding类型的参数,取得编码的方式:Encoding.Default、 Encoding.UTF8、Encoding.GetEncoding(“GBK”)产生乱码的原因(只有文本文件才会乱码):文本文件存储时采用的编码,与读取时采用的编码不一致,就会造成乱码问题。•GB2312:兼容ASCII,包含中文。

-霄-的博客 1006
上一篇: CreateRemoteThread远程注入 使用例子
下一篇: 驱动编译
goodwinds
博客等级 码龄20年 66粉丝 37原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值