You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将一个方法的返回值存入另一个方法的字符串变量

解决方法:获取自定义方法返回值并显示文件编码

你当前的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;
}

关键说明

  1. 调用自定义方法:直接用GetEncoding(theFile)获取返回的Encoding对象,而非系统内置的同名方法
  2. 获取编码名称:
    • WebName:返回标准编码标识(如utf-8、unicode)
    • EncodingName:返回更易读的友好名称(如UTF-8、Unicode (UTF-16))
  3. 局部变量优化:将StrFileName声明为局部变量,避免依赖未定义的类字段

内容的提问来源于stack exchange,提问作者Ed Swafford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 05:12:46