简体   繁体   中英

Convert text of a C# project into 1 text file

So I'm doing Google Code Jam, and for their new format I have to upload my code as a single text file.

I like writing my code as properly constructed classes and multiple files even when under time pressure (I find that I save more time in clarity and my own debugging speed than I lose in wasted time.) and I want to re-use the common code.

Once I've got my code finished I have to convert from a series of classes in multiple files, to a single file.

Currently I'm just manually copying and pasting all the files' text into a single file, and then manually massaging the usings and namespaces to make it all work.

Is there a better option? Ideally a tool that will JustDoIt for me? Alternatively, if there were some predictable algorithm that I could implement that wouldn't require any manual tweaks?

  1. Write your classes so that all "using"s are inside "namespace"
  2. Write a script which collects all *.cs files and concatenates them

在此处输入图片说明

This is probably not the most optimal way to do this but this is a algorithm which can do what you need:

  • loop through every file and grab every line starting with " using " -> write them to a temp file/buffer
  • check for duplicates and remove them
  • get the position of the first ' { ' after the charsequence " namespace "
  • get the position of the last ' } ' in the file
  • append the text in between these two positions onto a temp file/buffer
  • append the second file/buffer to the first one
  • write out the merged buffer

It is very subjective. I see the algorithm as the following in pseudo code:

usingsLines = new HashSet<string>();
newFile = new StringBuilder();
foreeach (file in listOfFiles)
{
    var textFromFile = file.ReadToEnd();
    var usingOperators = textFromFile.GetUsings();
    var fileBody = textFromFile.GetBody();
    newFile+=fileBody ;
}
newFile = usingsLines.ToString() + newFile;
// As a result if will have something like this
// using usingsfromFirstFile;
// using usingsfromSecondFile;
// 
// namespace FirstFileNamespace
// {
// ...
// }
// 
// namespace SecondFileNamespace
// {
// ...
// }

But keep in mind this approach can lead to conflicts in namespaces if two different namespaces contan the same classes etc. To solve it you need to fix it manually, or rid of using operator and use fullnames with namespaces.

Also these few links may be useful: Merge files , Merge file in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM