无法将一个方法的返回值存入另一个方法的字符串变量
解决方法:获取自定义方法返回值并显示文件编码
你当前的CheckContent方法错误调用了.NET内置的Encoding.GetEncoding(string)方法(该方法接收编码名称而非文件名),而非你自己定义的GetEncoding(string filename)静态方法。要获取自定义方法的返回值,直接调用它并接收结果即可。
修正后的完整代码
private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string StrFileName = openFileDialog1.FileName; CheckContent(StrFileName); } } private void CheckContent(string theFile) { // 调用自定义的GetEncoding方法,接收返回的Encoding对象 Encoding fileEncodingObj = GetEncoding(theFile); // 获取编码的标准名称(如"utf-8"),或用EncodingName获取友好名称(如"UTF-8") string fileEncoding = fileEncodingObj.WebName; MessageBox.Show($"The encoding of the file is: {fileEncoding}", "Name Randomizer", MessageBoxButtons.OK, MessageBoxIcon.Information); } public static Encoding GetEncoding(string filename) { // Read the BOM var bom = new byte[4]; using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read)) { file.Read(bom, 0, 4); } // Analyze the BOM if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7; if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8; if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true); //UTF-32BE // 未知编码时返回ASCII,也可改为返回null自行处理 return Encoding.ASCII; }
关键说明
- 调用自定义方法:直接用
GetEncoding(theFile)获取返回的Encoding对象,而非系统内置的同名方法 - 获取编码名称:
WebName:返回标准编码标识(如utf-8、unicode)EncodingName:返回更易读的友好名称(如UTF-8、Unicode (UTF-16))
- 局部变量优化:将
StrFileName声明为局部变量,避免依赖未定义的类字段
内容的提问来源于stack exchange,提问作者Ed Swafford
相关产品推荐
相关产品推荐

