我在资源文件 (.resx) 中添加了一些现有的配置文件。我编写了以下代码来从资源文件中获取文件并将这些文件写入在 Settings.settings 文件中配置的目标文件夹中。
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Fs.ExtendedImporter.Application.Configuration.SampleConfigFiles.ExampleFiles.resx"))
{
if (resourceStream != null)
{
using (var resourceReader = new ResourceReader(resourceStream))
{
foreach (DictionaryEntry resource in resourceReader)
{
string resourceName = (string)resource.Key;
byte[] resourceData = (byte[])resource.Value;
string destinationFile = Path.Combine(Settings.Default.ApplicationConfiguration, resourceName);
if (!File.Exists(destinationFile))
{
File.WriteAllBytes(destinationFile, resourceData);
}
}
}
}
else
{
Logger.Log.Error("Resource file not found.");
}
}
但是在此代码中,resourceSteam 变量返回 null。
我已检查资源(.resx)文件属性并确保构建操作设置为嵌入式资源。
dotpeek 截图-
GetManifestResourceStream() 方法中的命名空间也是正确的。
可能是什么问题?我感谢您的宝贵帮助。
最后,我找到了
ResourceManager
作为替代方案,它对我有用 -
// Create a ResourceManager for the resource file
var resourceManager = new ResourceManager(
"Fs.ExtendedImporter.Application.Configuration.SampleConfigFiles.ExampleFiles",
Assembly.GetExecutingAssembly());
// Get all resource names in the resource file
var resourceSet = resourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true);
foreach (var resource in resourceSet)
{
var resourceEntry = (System.Collections.DictionaryEntry)resource;
string resourceName = resourceEntry.Key.ToString();
object resourceValue = resourceEntry.Value;
string destinationFile = Path.Combine(Settings.Default.ApplicationConfiguration, resourceName + ".xml");
// Handle string resources
if (resourceValue is string stringValue)
{
if (!File.Exists(destinationFile))
{
File.WriteAllText(destinationFile, stringValue);
}
}
// Handle binary resources (byte arrays)
else if (resourceValue is byte[] binaryValue)
{
if (!File.Exists(destinationFile))
{
File.WriteAllBytes(destinationFile, binaryValue);
}
}
}