Environment:
I'm using Windows 7 64bit with Notepad++ 5.9.3, Visual Studio 2010 Ultimate, C# .NET 2.0.
Problem:
So i face a really annoying problem today,
I had an array with 400 lines written in C#.
The problem is that, the list was reversed from the order i wanted.
I had an array with 400 lines written in C#.
The problem is that, the list was reversed from the order i wanted.
Example:
The array i have:
The array i need:
Like i said it's a 400 lines array...
Research:
I really needed this reversed, i tried Notepad++ with several plugins like TextFX without any success, i actually found out that it's possible to do it by recording a Macro in the Notepad++, but it's like not my thing.
So i used my best friend! C# :)
I'll make a quick explanation of what i'm doing and then just paste the code.
Solution:
So i made a Console App that gets a file path from the application arguments.
It reads all the lines and pushs them into a Stack then writes it to a new file using Pop :)
Heres the code: (Just compile and it works)
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
if (args.Length == 0)
{
Console.WriteLine("Please enter a file path to reverse in the console arguments.");
}
else
{
string p = args[0];
string o = Path.GetDirectoryName(p) + Path.PathSeparator + Path.GetFileNameWithoutExtension(p) + "Reversed" + Path.GetExtension(p);
Console.WriteLine(o);
try
{
String line;
Stack< string > lines = new Stack< string >();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(p))
{
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
lines.Push(line);
}
// create a writer and open the file
// The using statement also closes the StreamWriter.
using (TextWriter tw = new StreamWriter(o))
{
// write a line of text to the file
while (lines.Count > 0)
tw.WriteLine(lines.Pop());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read/written:");
Console.WriteLine(e.Message);
}
Console.WriteLine("Reversed.");
}
}
Console.ReadLine();
}
}
No comments:
Post a Comment