Search code examples
visual-studiovisual-studio-extensions

Is there a facility to select a section of code and save it a seperate file in Visual Studio 2019?


I work with large html files that I would like to fragment into seperate files. The process of doing this is quite tedious as it requires copying the code, creating a new file, pasting it in the new file, and then selecting a folder and a name to save it under.

Is there a built-in shortcut or extension in Visual Studio 2017 and higher for making this easier?


Solution

  • You can automate it in Visual Studio with my Visual Commander extension. Select the code and call the following command (C# language):

    public class C : VisualCommanderExt.ICommand
    {
        public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
        {
            string currentFileName = DTE.ActiveDocument.FullName;
            string newFileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(currentFileName), System.IO.Path.GetFileNameWithoutExtension(currentFileName) + "NewPart" + System.IO.Path.GetExtension(currentFileName));
            EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
            System.IO.File.WriteAllText(newFileName, ts.Text);
        }
    }