How can I read string resource file? I have tried this already but I couldn't get the value. For editing it later I couldn't do anything. How can I edit it later programmaticaly? I want to edit its value with a string that I get from textbox.
Assembly assembly = this.GetType().Assembly;
manager = new ResourceManager("StringResources.Strings", assembly);
value = manager.GetString("Name");
For changing its value I tried to do this but it gives me an error does not contain a definition for Current. I try these in windows form.
Application.Current.Resources["Name"] = "abcd";
Please give me an advice
Thanks in advance
You cannot edit a resource string. If you want to store some string that you can alter programatically you should use a configuration file, or, even better user or app settings (that are actually a wrapper around the configuration file).
The reason that you can't change a resource string at runtime, is because the resource is compiled into your executable. If you reverse engineer the compiled *.exe or *.dll file, you can actually see your string in the code. Editing an already compiled executable file is never a good idea (unless you're trying to hack it), but when you try to do it from the executables code, it just plain impossible, as the file is locked during execution.
You can read more about user settings on MSDN.
You should check out the link, as it contains detailed instructions with screenshots as to how to set your settings through GUI.
In brief, you right click your project->Properties->Settings. Now, you'll see a table where you can add, edit and remove user settings. Once you create a user setting you can use it like this:
//Read
String settingValue = Settings.Default.TestSetting;
//Write
Settings.Default.TestSetting = "newVal";
//Write settings to disk
Settings.Default.Save();
Related
I have an application that I am developing that is made with Window Forms. For localizing all my Labels, ToolStripMenuItems, Buttons, etc I use resx resource files. Specifically to localize my application for German, I open my Main.en-CA.resx file in winres. I then go through all the terms found in the form and change them to their German translation. I then save the file to Main.de-DE.resx. I now have a Main.en-CA.resx file and a Main.de-DE.resx file. In my code I then only have to change the current culture to whatever language I want and apply the change to all my Labels, Controls, Buttons, etc. For example something like this:
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language);
// Must re-apply resources after changing the culture
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
resources.ApplyResources(this, "$this");
foreach (Control c in this.Controls)
{
resources.ApplyResources(c, c.Name);
}
This seems to work great for all Labels etc that do not change. I do however have entries that are changed. For example I might have a dropdown ComboBox that is filled with the entries: "Apple", "Banana", "Orange". Or I might have some error messages: "Missing Input", "Cannot find xml file" that are only sometimes displayed. Now I suppose maybe for the error messages I could just have Labels and selectively change their visibility depending on whether they need to be shown, however for the dropdown ComboBox these entries might change depending on say which file the user loads.
I am wondering then, is there a way to store these entries in the resx files and then access them from my code. I tried opening the resx files and adding them manually (i.e. without using winres) but attempting to do this resulted in the warning:
You are trying to edit a resource file that is a part of another project item (such as a form or control). Editing this item could corrupt the project item, and you will have to recover it by hand. In addition, changes made to this resource file may be lost if further changes are made to the project item.
Do you really want to edit this file?
This sounded like a bad idea so I didn't try that any further. Additionally I am not sure on how I would access the terms in the file manually. I am very new to windows forms and resource files (this is my first time using them) so I realize this might be a simple question but I have had trouble finding information on how exactly to do this.
Ok as it turns out I have uncovered how I can achieve what I am looking for. Ok from the SO post I can access any strings stored in the files Resource.resx by the code:
myLabel.Text = Properties.Resources.MissingController;
where MissingController is a key (i.e. Name) in the file Resources.resx.
Therefore all I need to do is add additional resource files such as Resource.de-DE.resx in the case of German and fill in the translations (i.e. the values in the resource file) corresponding to the same keys (i.e. the names in the resource file).
The Resources.resx file looks like:
and the Resources.de-DE.resx looks like:
As mentioned in the question I had already created some resource files for translating my forms but I had used winres. Whereas they had been located under my Main.cs [Design] file, the Resources.resx and Resources.de-de.resx are located under Properties. Because I had used winres to make my resx files I think that meant I was not supposed to manually edit them hence the warning it gave?? I'm still not 100% sure about this.
Regardless I can now just manually add terms to my Resource.resx file as well as create different versions of this file for different languages and the localization will work. When right clicking on Properties and going Add->New Item and then selecting Resource, if you do not see the Resource file type as an option (as happened to me) then that might mean you need to add the development tools that did not get installed with your version of visual studio. You can achieve this by just running the visual studio installer again and clicking modify and adding the .NET development tools.
This question already has answers here:
What is the best way to store user settings for a .NET application?
(8 answers)
Closed 5 years ago.
My program must produce files from some given data. I'm dealing with PDFs and Excel documents. How do I allow the user to set the directory where the files will be saved? I'm not referring to SaveFileDialog where the user must choose the directory every time.
I want the files to automatically be saved to the directory previously specified by the user. Something to this effect:
Most immediate solution I can think of is to store the directory in a file and read it every time a file is to be saved.
I also read about Properties.Settings.Default.Save(), but is it relevant to my case?
Use FolderBrowserDialog to get the folder...
https://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog(v=vs.110).aspx
Get the folder's path.
folderName = folderBrowserDialog1.SelectedPath;
Then go into your project properties (Project menu > Project Name Properties), and click the settings tab. Add a new setting with a name of your choice, like SaveLocation with the type of string. Then you can save it like so...
Settings.Default["SaveLocation"] = folderName;
Properties.Settings.Default.Save();
And then, obviously, retrieve it like so...
string saveLocation = Settings.Default["SaveLocation"]
Read more about saving application settings here: https://msdn.microsoft.com/en-us/library/a65txexh.aspx
You may care to use the registry to store information between sessions. This will require that you have admin privileges. Since this is winform it may be.
I am relatively new to C#, however I do have some basic knowledge of code from courses in high school and university. However, there is one thing I have not been able to figure out over the years. I am currently making a Form Application for a database system that stores information in a List using Visual Studios 2010.
On my main form; when the save button is pressed, the information is then serialized into an XML file. When the information is loaded, the information is then deserialized and put into the List for use in the code. All this is working correctly.
This process of saving and loading is done based on a string which contains the file path. This string is the location of a folder on my desktop (I put it there for easy access), and I am able to change the string in the code to basically move where the information is stored.
However, I have a separate "Admin" form which is able to change this file path string. When the user clicks the button to change the file path, I get the input from a text box, check its formatting, move the current file to the new location and update the location for the save method so changes can be saved before the program is closed. From there, the program reacts the same way as if I had changed the string from inside the code.
The problem occurs when I close the program. I do not know how to tell the program when it runs again that the location has been changed from the default and look for the file in the new location. The program reacts just like the file was missing (like it should) when it looks in the default location.
So basically, how do I tell the program that the save location was changed from when it was last run so it knows to load the info from a new location?
I have tried looking for an answer since high school (about 2 years ago) and have not found a solution. As a result I usually just keep the save location as the default (which I set it to) and don't try to change it. But this time, its important that the save location can be customized. My experience with Visual Studios is limited, as everything I know is from messing around with the program and looking up stuff when needed.
If needed, I can post snippets of my code. Thank you in advance!
It seems like what you really want is to save some user-defined settings for recall at run-time. Here is a MSDN link describing some basic conventions for storing / retrieving these settings.
https://msdn.microsoft.com/en-us/library/bb397750(v=vs.110).aspx
A *.config file would suffice (depending on the scale of the application).
Otherwise, you may want to go down the route of storing these settings in a database (if the scale is rather large, or if user-authentication is required for the application).
Here is another previous question dealing with this same subject (regarding App.config files):
What is App.config in C#.NET? How to use it?
I recommend using a config file where the .exe is, and write the location there, then read it in on program startup.
In particular .net provides this class which can manage your config file for you (assuming you have an app.config in your solution, otherwise create one)
https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings(v=vs.110).aspx
I am working on an application with Spring.Net and Windows forms. I would like to prevent users to change the Spring configuration file, something like setting the configuration file as readonly. I read the Spring.Net documentation and I found nothing, I looked on visual studio's side but I did not find how to set a file as Readonly. The only thing I found is to encrypt the app.config file, it is working but it does not prevent user changes.
Do you have any idea?
Really preventing a change will be hard to impossible...
BUT usually it should be enough to be able to recognize whether it has been changed... to achieve this you basically need to implement some variation of the following scheme:
Create a hash of the file (together with a salt)
Store that value in your app.config
In your application read the file and recalculate that hash (with the same hash)
IF that value matches what is in your app.config all is fine, otherwise it has been changed and you need to take the appropriate action
To take the above a step further:
You could embed a copy of the file as an "embedded resource" into your application (EXE/DLL) and replace the file on disk on startup with the content of that resource - this way you make sure that the file is always what your application expects.
DISCLAIMER: the above scheme won't stop a really determined "attacker/hacker...".
I've seen this solution proposed, but doesn't seem to work for me:
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = “NewValue”;
oConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
It successfully changes the value in memory, but does not save it back to the config file.
I'm trying to do this in a Wpf app, if that makes any difference.
Or is there a preferred way to save user settings to a file?
If your app is installed in \Program Files\ then it may not have permissions to write to the file. Generally, app.config files are modified by hand (in my experience, at least). If you want to persist user preferences, you should look into a .settings file as these are created in the %appdata% (or %localappdata%) directory, which is under the user's directory.
My guess is that using OpenExeConfiguration does not actually open the associated file. For example, you could be running from a XAP, where there would still be a .exe.config inside the .xap, but it doesn't map to an actual file on the filesystem.
You could probably check this by seeing if oConfig.HasFile is true or not.
If my guess is correct, then you'll need to use the OpenExeConfiguration(string) overload; the sample on the MSDN page has a reasonable way to get the right filename, although my first instinct was instead to try System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.