如何将Resx文件自动生成Designer.cs文件

        static void GenerateDesignerFile(FileInfo fileInfo)
        {
            if (fileInfo.Name.Equals("Resources.resx", StringComparison.OrdinalIgnoreCase) == false)
            {
                return;
            }

            string designerFilePath = fileInfo.FullName.Replace(".resx", ".designer.cs");
            FileInfo designerFileInfo = new FileInfo(designerFilePath);

            if (designerFileInfo.Attributes.ToString().IndexOf("ReadOnly") != -1)
            {
                designerFileInfo.Attributes = FileAttributes.Normal;
            }

            Regex reg = new Regex("(?<=(namespace ))[.\\s\\S]*?(?=( ))", RegexOptions.Multiline | RegexOptions.Singleline);
            string fullText = File.ReadAllText(designerFileInfo.FullName);
            string designerNamespace = reg.Match(fullText).Value;
            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            string[] unmatchedElements;

            ListDictionary resourceList = new ListDictionary();

            using (ResXResourceReader rsxr = new ResXResourceReader(fileInfo.FullName))
            {
                rsxr.BasePath = fileInfo.Directory.FullName;
                rsxr.UseResXDataNodes = true; 

                foreach (DictionaryEntry d_loopVariable in rsxr)
                {
                    resourceList.Add(d_loopVariable.Key, d_loopVariable.Value);
                }
            }

            System.CodeDom.CodeCompileUnit code = System.Resources.Tools.StronglyTypedResourceBuilder.Create(
                resourceList,
                "Resources",
                designerNamespace,
                codeProvider,
                true,
                out unmatchedElements); // Needs System.Design.dll

            using (StreamWriter writer = new StreamWriter(designerFileInfo.FullName, false, System.Text.Encoding.UTF8))
            {
                codeProvider.GenerateCodeFromCompileUnit(code, writer, new System.CodeDom.Compiler.CodeGeneratorOptions());
            }
        }

 

posted on 2012-12-04 15:41  seacryfly  阅读(3001)  评论(1编辑  收藏  举报