从ResXRersourcewriter生成的资源文件创建designer.cs文件

我有一个生成.resx资源文件的程序。 这些资源文件用于其他项目,与生成资源文件的项目不在同一解决方案中。

我现在想知道,如果可以从资源文件生成designer.cs文件,那么您可以直接访问资源而无需使用resxresourcereader。

打开resx文件,在它的工具栏上有一个Access Modifier菜单。 将此设置为Public 。 这将生成*.Designer.cs文件。

在此处输入图像描述

如果将文件添加到Visual Studio项目,则必须将.resx文件的“ Custom Tool属性设置为ResXFileCodeGenerator 。 然后VS会自动创建所需的设计器文件。

在一个项目中,我制作了一个T4脚本,在项目中扫描所有图像的文件夹,然后单击创建相应的资源文件。

以下是T4脚本中所需的部分:

 var rootPath = Path.GetDirectoryName(this.Host.TemplateFile); var imagesPath = Path.Combine(rootPath, "Images"); var resourcesPath = Path.Combine(rootPath, "Resources"); var pictures = Directory.GetFiles(imagesPath, "*.png", SearchOption.AllDirectories); EnvDTE.DTE dte = (EnvDTE.DTE)((IServiceProvider)this.Host) .GetService(typeof(EnvDTE.DTE)); EnvDTE.Projects projects = dte.Solution.Projects; EnvDTE.Project iconProject = projects.Cast().Where(p => p.Name == "Icons").Single(); EnvDTE.ProjectItem resourcesFolder = iconProject.ProjectItems.Cast().Where(item => item.Name == "Resources").Single(); // Delete all existing resource files to avoid any conflicts. foreach (var item in resourcesFolder.ProjectItems.Cast()) { item.Delete(); } // Create the needed .resx file fore each picture. foreach (var picture in pictures) { var resourceFilename = Path.GetFileNameWithoutExtension(picture) + ".resx"; var resourceFilePath = Path.Combine(resourcesPath, resourceFilename); using (var writer = new ResXResourceWriter(resourceFilePath)) { foreach (var picture in picturesByBitmapCollection) { writer.AddResource(picture.PictureName, new ResXFileRef(picture, typeof(Bitmap).AssemblyQualifiedName)); } } } // Add the .resx file to the project and set the CustomTool property. foreach (var resourceFile in Directory.GetFiles(resourcesPath, "*.resx")) { var createdItem = resourcesFolder.Collection.AddFromFile(resourceFile); var allProperties = createdItem.Properties.Cast().ToList(); createdItem.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator"; } 

我稍微讨论了上面的代码,因为在我真正的解决方案中,我为每张图片使用自定义类而不是简单的文件名,以便在不同的子文件夹中支持相同的文件名(通过使用命名空间的文件夹结构的一部分)代)。 但是对于第一枪,上面应该对你有所帮助。

右键单击Resources.resx并选择“运行自定义工具”。

您也可以在代码中执行此操作:(取自此处: msdn )

  StreamWriter sw = new StreamWriter(@".\DemoResources.cs"); string[] errors = null; CSharpCodeProvider provider = new CSharpCodeProvider(); CodeCompileUnit code = StronglyTypedResourceBuilder.Create("Demo.resx", "DemoResources", "DemoApp", provider, false, out errors); if (errors.Length > 0) foreach (var error in errors) Console.WriteLine(error); provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions()); sw.Close(); 

您需要引用system.design.dll

这对我也有用:双击并打开resx文件,添加虚拟资源,单击“保存”。 生成.designer.cs文件。

如果您删除它或将其添加到.gitignore,因为您认为您不需要它。 这是您重新生成文件的方式。

转到Access修饰符并将其从(公共/内部)更改为“无代码生成”

现在把它放回公共/内部。 VS将为您重新生成Designer文件。