简体   繁体   English

将图像添加到项目资源文件夹运行时

[英]Add image to project resources folder runtime

I have created a method to save an uploaded image to my project resources folder. 我创建了一种将上传的图像保存到我的项目资源文件夹中的方法。 The image is correctly added to my resources folder, but I can't use the image because I can't set the build action. 该图像已正确添加到我的资源文件夹中,但是由于无法设置构建动作,因此无法使用该图像。 Where can I store uploaded images, which folder? 我可以在哪里存储上传的图像,哪个文件夹? I read about the bin directory but is this good practice? 我读到了bin目录,但这是一种好习惯吗?

Resources is a folder under my project. 资源是我项目下的文件夹。 As you can see in the screenshot below I can't set the build action of my uploaded image (beats_1.jpg). 如您在下面的屏幕快照中所见,我无法设置上传图像(beats_1.jpg)的构建动作。

在此处输入图片说明

Code to save the image 保存图像的代码

var path = string.Format(@"{0}\Resources\Images\{1}", Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, GiftImageFileName);
var resizedImage = GiftImage.CreateResizedImage(100, 100, 0);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(resizedImage));
using (FileStream stream = new FileStream(path, FileMode.Create))
{
    encoder.Save(stream);
}

OK, so i'm guessing that you want to perform this process BEFORE you build, and therefore your file is included in the compiled output as a resource and you can reference it in the compiled executable. 好的,所以我猜测您想在构建之前执行此过程,因此您的文件作为资源包含在已编译的输出中,您可以在已编译的可执行文件中引用它。

There are two approaches to this, one is the quick and dirty, one is more complex and correct. 有两种解决方法,一种是快速而又肮脏的,一种是更复杂且正确的。

Quick and dirty: (This should be performed when the Visual Studio Solution is not loaded) 快速又肮脏:(应在未加载Visual Studio解决方案时执行)

  • Open the Project CSPROJ file via an XML modification library in your C# code (eg using XDoc). 通过C#代码中的XML修改库(例如,使用XDoc)打开Project CSPROJ文件。

  • Programmatically add the following under the <Project> section 以编程方式在<Project>部分下添加以下内容

      <ItemGroup> <Resource Include="Resources\\Images\\beats_1.png" /> <Resource Include="Resources\\Images\\beats_2.png" /> <Resource Include="Resources\\Images\\beats_n.png" /> </ItemGroup> 
    • Save the CSPROJ file 保存CSPROJ文件
    • Compile your project 编译项目

More complex and correct: - Use a VSPackage visual studio add-in to modify the current loaded project and add new resource items. 更复杂,更正确:-使用VSPackage visual studio加载项来修改当前加载的项目并添加新的资源项。 - See here: How do I programmatically add a file to a Solution? -请参阅此处: 如何以编程方式将文件添加到解决方案?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM