C#编写项目编码格式转换器

本人是JAVA开发 由于开发的人多了 有的人开发环境编码格式也不同 有的是GBK 有的是UTF-8 代码中更是层出不穷

直接导致项目中中文的类乱码 写代码不能加注释的囧地 为了解决此问题编写了此软件  分享出来希望能帮助到其他人

部分代码如下:

 

 public int[] Count=new int[3];//存储计数信息
        public string SelectPath = null;//存储选择的路径
        private Profile profile = new Profile();
        string confitemp = "Configuration";//配置的总节点
        /// <summary>
        /// 判断文件编码格式是什么
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
         public static Encoding GetEncoding(FileStream stream)
        {
            Encoding targetEncoding = Encoding.Default;
            if (stream != null && stream.Length >= 2)
            {
                //保存文件流的前4个字节
                byte byte1 = 0;
                byte byte2 = 0;
                byte byte3 = 0;
                byte byte4 = 0;
                //保存当前Seek位置
                long origPos = stream.Seek(0, SeekOrigin.Begin);
                stream.Seek(0, SeekOrigin.Begin);
                int nByte = stream.ReadByte();
                byte1 = Convert.ToByte(nByte);
                byte2 = Convert.ToByte(stream.ReadByte());
                if (stream.Length >= 3)
                {
                    byte3 = Convert.ToByte(stream.ReadByte());
                }
                if (stream.Length >= 4)
                {
                    byte4 = Convert.ToByte(stream.ReadByte());
                }
                //根据文件流的前4个字节判断Encoding
                //Unicode {0xFF, 0xFE};
                //BE-Unicode {0xFE, 0xFF};
                //UTF8 = {0xEF, 0xBB, 0xBF};
                if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
                {
                    targetEncoding = Encoding.BigEndianUnicode;
                }
                if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
                {
                    targetEncoding = Encoding.Unicode;
                }
                if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
                {
                    targetEncoding = Encoding.UTF8;
                }
                //恢复Seek位置       
                stream.Seek(origPos, SeekOrigin.Begin);
            }
            return targetEncoding;
        }
         /// <summary>
         /// 通过给定的文件流,判断文件的编码类型
         /// </summary>
         /// <param name="fs">文件流</param>
         /// <returns>文件的编码类型</returns>
         public Encoding GetType(FileStream fs)
         {
             byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
             byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
             byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
             Encoding reVal = Encoding.Default;
             BinaryReader r = new BinaryReader(fs,Encoding.Default);
             int i;
             int.TryParse(fs.Length.ToString(), out i);
             byte[] ss = r.ReadBytes(i);
             if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
             {
                 reVal = Encoding.UTF8;
             }
             else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
             {
                 reVal = Encoding.BigEndianUnicode;
             }
             else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
             {
                 reVal = Encoding.Unicode;
             }
             r.Close();
             return reVal;
         }
         /// <summary>
         /// 判断是否是不带 BOM 的 UTF8 格式
         /// </summary>
         /// <param name="data"></param>
         /// <returns></returns>
         private bool IsUTF8Bytes(byte[] data)
         {
             int charByteCounter = 1;  //计算当前正分析的字符应还有的字节数
             byte curByte; //当前分析的字节.
             for (int i = 0; i < data.Length; i++)
             {
                 curByte = data[i];
                 if (charByteCounter == 1)
                 {
                     if (curByte >= 0x80)
                     {
                         //判断当前
                         while (((curByte <<= 1) & 0x80) != 0)
                         {
                             charByteCounter++;
                         }
                         //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                         if (charByteCounter == 1 || charByteCounter > 6)
                         {
                             return false;
                         }
                     }
                 }
                 else
                 {
                     //若是UTF-8 此时第一位必须为1
                     if ((curByte & 0xC0) != 0x80)
                     {
                         return false;
                     }
                     charByteCounter--;
                 }
             }
             if (charByteCounter > 1)
             {
                 throw new Exception("非预期的byte格式");
             }
             return true;
         }
         private void butttrun_Click(object sender, EventArgs e)
         {
             this.butttrun.Enabled = false;
             this.buttonSelect.Enabled = false;             
             Count = new int[3];//存储计数信息
             if (SelectPath != null)
             {
                 this.Tag = this.Text;
                 this.Text = "正在努力拷贝项目请稍候....(请勿关闭本软件)";
                 List<string> files = GetFileName(SelectPath);//要转码的所有文件
                 int copycount = GetCopyFileCount(SelectPath, files);
                 this.Text = "正在努力转码 请稍候....(请勿关闭本软件)";
                 foreach (var sub in files)
                 {
                     Transcoding(sub);                    
                 }
                 this.Text = "" + this.Tag;
                 LogBLL.Err("转码总计: 成功" + Count[0] + "个 失败 " + Count[1] + "个 不存在 " + Count[2] + "个 拷贝" + copycount + "个");
                 MessageBox.Show(this, "转换文件总计: 成功" + Count[0] + "个 失败 " + Count[1] + "个 不存在 " + Count[2] + "个 拷贝" + copycount + "个", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
             }
             else
             {
                 MessageBox.Show(this, "请先选择您要处理的文件", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
             }
             this.butttrun.Enabled = true ;
             this.buttonSelect.Enabled = true;
         }
        /// <summary>
        /// 获取资源文件所有文件
        /// </summary>
        /// <param name="SelectPath"></param>
        /// <returns></returns>
         public int GetCopyFileCount(string SelectPath, List<string> files) 
         {
             int i = 0;
             string[] fileName = Directory.GetFiles(SelectPath, "*.*", SearchOption.AllDirectories);
             foreach (var file in fileName)
             {
                 if (!files.Contains(file))
                 {
                     try
                     {
                         int lastlen = file.LastIndexOf("\\");//结束的/
                         int startlen = file.IndexOf("\\");//开始的/
                         string temp = file.Substring(lastlen + 1);
                         string tempqian = file.Substring(startlen + 1, (lastlen - startlen) - 1);
                         Generate(tempqian);//生成一个文件夹
                         File.Copy(file, System.Environment.CurrentDirectory + "\\" + tempqian + "\\" + temp, true);
                         i++;
                     }
                     catch (Exception e)
                     {
                         LogBLL.Err("文件[" + file + "]拷贝失败[" + e .Message+ "]");
                     }
                 }                
             }
             return i;
         }
        /// <summary>
        /// 转码指定文件转换为固定编码格式
        /// </summary>
         public void Transcoding(string filename)
         {
             Encoding en2 = Encoding.Default;
             if (checkBoxutf8.Checked)
             {
                 en2 = Encoding.UTF8;
             }
             else if (checkBoxgbk.Checked)
             {
                 en2 = Encoding.GetEncoding("GBK");
             }
             else
             {
                 en2 = Encoding.GetEncoding("GB2312");
             }
             if (File.Exists(filename))
             {
                 try
                 {
                     string fstr = null;
                     FileStream fs = new FileStream(filename, FileMode.Open);
                     Encoding targetEncoding = GetType(fs);
                     fs.Close();
                     using (StreamReader sr = new StreamReader(filename, targetEncoding))
                     {
                         fstr = sr.ReadToEnd();
                     }
                     int lastlen=filename.LastIndexOf("\\");//结束的/
                     int startlen=filename.IndexOf("\\");//开始的/
                     string temp = filename.Substring(lastlen+1);
                     string tempqian = filename.Substring(startlen+1, (lastlen - startlen)-1);
                     //Generate(tempqian);//生成一个文件夹
                     using (StreamWriter st = new StreamWriter(tempqian + "\\" + temp, false, en2))
                     {
                         st.Write(fstr);
                     }
                     Count[0] = Count[0]+1;
                     LogBLL.Err("文件[" + filename + "]转换成功");
                 }
                 catch (Exception e)
                 {
                     Count[1] = Count[1]+1;
                     LogBLL.Err("文件[" + filename + "]转换失败[" + e .Message+ "]");
                 }
             }
             else
             {
                 Count[2] = Count[2]+1;
                 LogBLL.Err("文件[" + filename + "]不存在");
             }             

         }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="dirMu"></param>
         private void Generate(string dirMu)
         {
             if (!Directory.Exists(dirMu))
             {
                 Directory.CreateDirectory(dirMu);
             }
             else
             {
                 //System.IO.DirectoryInfo path = new System.IO.DirectoryInfo(dirMu);
                 //foreach (System.IO.FileInfo f in path.GetFiles())
                 //{
                 //    f.Delete();
                 //}
             }
         }
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void buttonSelect_Click(object sender, EventArgs e)
         {
             this.butttrun.Enabled = false;
             this.buttonSelect.Enabled = false;
             FolderBrowserDialog FileDialogSelectFile = new FolderBrowserDialog();
             DialogResult result = FileDialogSelectFile.ShowDialog();
             SelectPath = FileDialogSelectFile.SelectedPath;
             if (result == DialogResult.OK && SelectPath != null)
             {
                 List<string> names = GetFileName(SelectPath);
                 if (names != null && names.Count > 0)
                 {
                     listViewFile.Clear();//清空列记录
                     ColumnHeader cZh = new ColumnHeader();//创建一个列
                     cZh.Text = "File Name"; cZh.Width = 433; //列名
                     listViewFile.Columns.AddRange(new ColumnHeader[] { cZh });//将这两列加入listView1
                     for (int i = 0; i < names.Count; i++)
                     {
                         ListViewItem lvi = new ListViewItem(new string[] { names[i] }, -1);//创建列表项
                         listViewFile.Items.Add(lvi);//将项加入listView1列表中               
                     }
                     MessageBox.Show(this, "总共发现" + names.Count+"相应的文件", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                 }
                 else
                 {
                     SelectPath = null;
                     MessageBox.Show(this, "没有找到相应的文件", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                 }
             }
             this.butttrun.Enabled = true;
             this.buttonSelect.Enabled = true ;
         }
        /// <summary>
        /// 获取一个路径下所有的文件
        /// </summary>
        /// <param name="SelectedPath"></param>
        /// <returns></returns>
         public List<string> GetFileName(string SelectedPath) 
         {
             List<string> Files = new List<string>();
             string Filter = profile.ContentValue(confitemp, "Filter");
             string[] files = Filter.Split('|');
             foreach (var item in files)
             {
                 if (item != null && item.StartsWith("*."))
                 {
                     string[] fileName = Directory.GetFiles(SelectedPath, item, SearchOption.AllDirectories);
                     Files.AddRange(fileName);
                 }                 
             }
             return Files;
         }
        /// <summary>
        /// UTF-8编码格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void checkBoxutf8_CheckedChanged(object sender, EventArgs e)
         {
             if (sender != null && sender.GetType()==typeof(CheckBox))
             {
                 CheckBox checkboxutf8=(CheckBox)sender;
                 if (checkboxutf8.Checked)
                 {
                     this.checkBoxgb2312.Checked = false;
                     this.checkBoxgbk.Checked = false;
                 }
             }
         }
        /// <summary>
        /// GBK编码格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void checkBoxgbk_CheckedChanged(object sender, EventArgs e)
         {
             if (sender != null && sender.GetType() == typeof(CheckBox))
             {
                 CheckBox checkboxgbk = (CheckBox)sender;
                 if (checkboxgbk.Checked)
                 {
                     this.checkBoxgb2312.Checked = false;
                     this.checkBoxutf8.Checked = false;
                 }
             }
         }
        /// <summary>
        /// GB2312编码格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void checkBoxgb2312_CheckedChanged(object sender, EventArgs e)
         {
             if (sender != null && sender.GetType() == typeof(CheckBox))
             {
                 CheckBox checkboxutf8 = (CheckBox)sender;
                 if (checkboxutf8.Checked)
                 {
                     this.checkBoxutf8.Checked = false;
                     this.checkBoxgbk.Checked = false;
                 }
             }
         }
        /// <summary>
        /// 加载次程序的时候启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void FileTranscoding_Load(object sender, EventArgs e)
         {
             if (File.Exists(profile.StartUpIniFileName))
             {}
             else
             {
                 profile.xieru();              
             }
         }    
    }
}

 转载请注明http://yuyu456.iteye.com/admin/blogs/1721470

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个很强大的工具, 能将c#代码片段、文件甚至工程直接转换成java代码,并能彻底解决外部引用的DLL问题,最强的是支持c#工程的直接转换,生成的Java代码质量也很不错。软件已破解,去除了未注册版最多只能转换1000行的限制,亲测可用!压缩包内含帮助文档,不过由于软件的使用很简单,帮助文档基本可以忽略。(小提示:如无法运行,请确认是否安装了.NET framework) 下面是一些英文介绍: C# to Java Converter features include: 1. Folder conversion: Entire folders of C# code files are converted to Java code files.(文件夹转换) 2. Code snippet and file conversion: Our snippet conversion accuracy is outstanding and does not require you to insert entire methods or classes. Heuristics are used to convert code fragments wit h missing declarations. (代码片段和文件转换) 3. Full support for the latest .NET code syntax: Generics and other newer C# features are converted where possible to the Java equivalent.(全面支持最新版的.NET语法) 4. Conversion options: You can specify numerous conversion options via our Options dialog. Code formatting options, custom type & member replacements, custom string replacements, and miscellaneous options. (可以指定转换规则) 5. File comparison feature: After converting a project or folder, you can compare original and converted files side-by-side. Comparing converted code to original code.(原代码与转换后代码的比较) 6. Running from the command line: C# to Java Converter can be launched directly for a specific project, folder, or file conversion from the command line. Command line.(命令行执行) 其他一些特点: 1. Converts all versions of C# code (2002, 2003, 2005, 2008, and 2010) (可以转换所有版本的C#代码) 2. Evaluates all referenced assemblies and .NET projects in order to resolve external references more completely.(能彻底解决外部引用的dll类库) 3. Converts C# ref parameters using Java generics 4. Superb conversions of all types of arrays 5. Handles the numerous coding alternatives and ambiguities of C# code 6. Flawless conversion of all aspects of inheritance and interfaces 7. Allows custom replacement of strings in the final converted code 8. Accurate even with poorly formatted C# code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值