Search code examples
c#visual-studio-2010exportresharper

How to export all the source code from Visual Studio into a text file?


I have a relatively large Visual Studio solution.

I need to export all the source code into a text file. I would also want to include a file name somewhere. How can I do so?

For example if I have a type

namespace MyProject.Core
{
    /// <summary>
    ///   Enumerates possible record status
    /// </summary>
    public enum RecordType
    {
        NonWearTime = 0,
        WearTime = 1,
        NotClassified = 2
    }
}

I want this to go to the output.txt file (or any other text format) and appear like so

//***********************************
//Filename: RecordType.cs
//***********************************
namespace MyProject.Core
{
    /// <summary>
    ///   Enumerates possible record status
    /// </summary>
    public enum RecordType
    {
        NonWearTime = 0,
        WearTime = 1,
        NotClassified = 2
    }
}

All the other types shall just be appended to the end of the file. I tried Resharper, but its header file options can only contain static text (I tried Filename: $FILENAME$) and the template option only applies to the newly created classes.

Folks, this is a study project, where I have to provide the source code along with a thesis.


Solution

  • This should do the trick

    string rootPath = @"path you your root folder";
    var header = "***********************************" + Environment.NewLine;
    
    var files = Directory.GetFiles(rootPath, "*.cs", SearchOption.AllDirectories);
    
    var result = files.Select(path => new { Name = Path.GetFileName(path), Contents = File.ReadAllText(path)})
                      .Select(info =>   
                          header
                        + "Filename: " + info.Name + Environment.NewLine
                        + header
                        + info.Contents);
    
    
    var singleStr = string.Join(Environment.NewLine, result);
    Console.WriteLine ( singleStr );
    File.WriteAllText(@"C:\output.txt", singleStr, Encoding.UTF8);
    

    Remarks: if you experience performance or memory inefficiencies, try to use StringBuilder instead and set it's Capacity at the start to the sum of all files contents. This will eliminate lots of redundant strings, created in last Select method.