How to set the default encoding for all files saved in Visual Studio
In Visual Studio, you can use the File -> Advanced Save Options menu item to save the file in the chosen encoding:
However, this option is available only for a single file:
What about automatically saving files in the specified encoding? Visual Studio has the ‘Save documents as Unicode when data cannot be saved in codepage’ option on the Environment | Documents option page in the IDE Options Dialog:
However, we still cannot select the specific default encoding for saved files. For instance, you cannot select the “Unicode (UTF-8 with signature) – Codepage 65001” like in Advanced Save Options dialog for all saved files by the IDE .
Let’s see if a CodeRush plug-in might help us here. The goal is to create a plug-in which will automatically save any files in the specified encoding. We will need to perform the following steps:
- Create a new DXCore plug-in
- Add an option page where we will allow selection of a default encoding and any other options
- Subscribe to the DocumentSaved DXCore event
- Resave the file once it was saved by Visual Studio
The first step is easy, you can learn more about creating plug-ins in the corresponding article – How to create a new CodeRush (DXCore) plug-in.
To learn more on how add a new plug-in option page, please refer to the following article – How to create a new plug-in Options page. The option page may look as follows:
The ‘Enabled’ option toggles the availability of the plug-in. In other words, if it is not enabled it will do nothing. The ‘Autoload file changes’ option is a mirror option of the ‘Auto-load changes, if saved’ Visual Studio option which can be found on the Environment | Documents option page of the IDE Options Dialog. This option should be checked, because if the IDE detects file changes outside the environment, the following dialog will appear for each file:
You can either manually toggle that option in the IDE Options Dialog, or toggle the option on the plug-in option page which will simply toggle the Visual Studio option for you. Bear in mind that toggling this option in the plug-in option page will toggle the Visual Studio option and save its state. In other words, it will change that option permanently.
To subscribe to the DocumentSaved event, simply choose it from the Properties window when the plug-in design surface is opened in the IDE:
In the DocumentSaved event handler, when a file is saved by the IDE, we can read it and re-save in any encoding as follows:
Of course, we are going to use the specified on the plug-in option page encoding and not a hard-coded value.
The plug-in source and binaries are attached (43,131 bytes, VS2010, C#).—– Products: DXCore Versions: 12.1 and up VS IDEs: 2008 and up Updated: Jul/31/2012 ID: D154