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

Jay*_*Tee 18 c# resx visual-studio

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

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

Pau*_*ing 43

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

在此输入图像描述

  • 当人们重命名resx时,项目文件/ TFS有时会混淆.只需删除.cs文件并使用此工具重新创建它就像一个魅力. (3认同)
  • 将访问修改器设置为公共工作完美无缺 - 谢谢. (2认同)

Oli*_*ver 5

如果将文件添加到Visual Studio项目,则必须Custom Tool.resx文件的属性设置为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<EnvDTE.Project>().Where(p => p.Name == "Icons").Single();
EnvDTE.ProjectItem resourcesFolder = iconProject.ProjectItems.Cast<EnvDTE.ProjectItem>().Where(item => item.Name == "Resources").Single();

// Delete all existing resource files to avoid any conflicts.
foreach (var item in resourcesFolder.ProjectItems.Cast<EnvDTE.ProjectItem>())
{
    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<EnvDTE.Property>().ToList();
    createdItem.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator";
}
Run Code Online (Sandbox Code Playgroud)

我已经将上述代码稍微弄平了,因为在我的实际解决方案中,我为每张图片使用了一个自定义类,而不是简单的文件名,以便在不同的子文件夹中也支持相同的文件名(通过使用命名空间的一部分文件夹结构)代)。但是,以上内容应该可以帮助您。


Mic*_*ann 5

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

  • 有没有办法在构建过程本身中做到这一点? (3认同)