Introduction
Here, I explain how to find the content in resource file and replace with specified content using console application. Visual Studio does not provide the functionality of find and replace for resources files.
Sample Code
Here, first I load the resource file into XDocument
namely xDocResElements in the resource file Element Name Data where I need to make changes.
try
{
XDocument xDocResElements= XDocument.Load(path);
bool changed = false;
foreach (XElement xEle in xDocResElements.Root.Elements())
{
if (xEle.Name.LocalName.ToLower() == "data")
{
XElement xValue = (xEle.Element("value") != null) ?
xEle.Element("value") : null;
if (xValue != null)
{
if (!string.IsNullOrEmpty(xValue.Value))
{
string sValue = xValue.Value;
if (!string.IsNullOrEmpty(findText) &&
!string.IsNullOrEmpty(replaceText))
{
if (sValue.Contains(findText))
{
changed = true;
xValue.Value = sValue.Replace(findText, replaceText);
}
}
}
}
}
}
if (changed)
{
resourceElements.Save(path);
Console.WriteLine("Successfully replaced the text, Path :" + path);
Console.ReadLine();
}
}
catch (Exception ex)
{
}
Replace Code
xValue.Value = sValue.Replace(findText, replaceText);
Here, I used string
function called Replace
. We can add more functionality like match only word or any place in the word, etc.
Saving to Location Code
resourceElements.Save(path);
After successful modifications have been made, we save to location.
Now, I will explain the process in a step by step manner.
Step 1
Create a Console application namely (FindAndReplaceContentinResourcefile
).
Step 2
Add Resource file to the project.
Step 3
Add some sample data as shown in the below image:
Step 4
Set resource file property namely "Copy to Output Directory as Copy Always".
Step 5
In the example, I used only single resource file but my code is useful for multiple resource files. if we are planning to work with multiple resource files, place all resource file in one folder . In the code, I am reading all resource files from a specified folder.
Sample Code to Read Multiple Resource Files
string resourceFilePath = AppDomain.CurrentDomain.BaseDirectory;
string[] resourceFileNames = System.IO.Directory.GetFiles(resourceFilePath,"*.resx");
foreach (string resFilepath in resourceFileNames)
{
updateResourcefile(resFilepath);
}
Here, I am taking BaseDirectrory
as the Resource folder.
System.IO.Directory.GetFiles(resourceFilePath,"*.resx");
This code is used to get the files that contain extension of .resx.
This is the time to run the Console application.
Download the source code and build and run the project.
First, it asks for what "Content" needs to be found in the resource file. and second input for Replace the find text in resource file. Here, we specified links.
In the output, it gives success message and path where the resource file is saved with changes.