C# Program Reading, Writing to Console, but Not to File - c#

I am trying to alphabetize all the words in a text file using C#. I am able to read the file and fill the list properly. I am then able to iterate through the list and print to the console. However, while I am iterating, I am also trying to write to an output file. I cannot seem to pinpoint why the output file is empty while the console has all the words printed properly. The file sortedProposal.txt is created, but is empty.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IO_Practice
{
class Program
{
static void Main(string[] args)
{
//get the directory of the text file
string directory = Directory.GetCurrentDirectory();
string cd = (Path.Combine(directory, #"..\..\"));
string infileHandle = cd + "AModestProposal.txt";
//print to screen for testing
Console.WriteLine(infileHandle);
//Holds all the words in the story
List<string> words = new List<string>();
//Holds the words from one line
string[] wordHolder;
//Holds each line as it's read
string line;
using (StreamReader sr = new StreamReader(infileHandle))
{
while ((line = sr.ReadLine()) != null)
{
//print to console
Console.WriteLine(line);
//split line into array
wordHolder = line.Split(' ');
//add array to vector
words.AddRange(wordHolder);
}
}
words.Sort();
//Debug
Console.WriteLine("Length of List: " + words.Count());
//create the outfile
string outfileHandle = cd + "sortedProposal.txt";
using(StreamWriter sw = new StreamWriter(outfileHandle)) {
foreach(string word in words)
{
sw.WriteLine(word);
//Debug
Console.WriteLine(word);
}
}
}
}
}

Related

C# Can StreamReader check current line number?

I tried making a script that would read a TXT file line by line, and change labels depending on what is inside.
Is there a way to check which line is being read?
This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class and you can just check the line string and matches with your desire label and replace with that.
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();
OR
using System;
using System.IO;
public class Example
{
public static void Main()
{
string fileName = #"C:\some\path\file.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Hope this will help you.
You can try querying file with a help of Linq:
using System.IO;
using System.Linq;
...
var modifiedLines = File
.ReadLines(#"c:\myInitialScript.txt") // read file line by line
.Select((line, number) => {
//TODO: relevant code here based on line and number
// Demo: return number and then line itself
return $"{number} : {line}";
})
// .ToArray() // uncomment if you want all (modified) lines as an array
;
If you want write modified lines to a file:
File.WriteAllLines(#"c:\MyModifiedScript.txt", modifiedLines);
If you insist on StreamReader, you can implement a for loop:
using (StreamReader reader = new StreamReader("c:\myInitialScript.txt")) {
for ((string line, int number) record = (reader.ReadLine(), 0);
record.line != null;
record = (reader.ReadLine(), ++record.number)) {
//TODO: relevant code here
// record.line - line itself
// record.number - its number (zero based)
}
}

Copy text to specific line

I didn't get why it isn't working..
Error shows like, newArraylist (line 13); newSreamReader (line 14, 24)
does not exist.
Any help will be appreciated.
using System;
using System.IO;
using System.Collections;
namespace InsertLineInTextFile
{
class Program
{
static void Main(string[] args)
{
string strTextFileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
ArrayList lines = new ArrayList();
StreamReader rdr = new StreamReader(strTextFileName);
string line;
while ((line = rdr.ReadLine()) != null) lines.Add(line);
rdr.Close();
if (lines.Count > iInsertAtLineNumber) lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
StreamWriter wrtr = new StreamWriter(strTextFileName);
foreach (string strNewLine in lines) wrtr.WriteLine(strNewLine);
wrtr.Close();
}
}
}
First, you have to think over what you're going to achieve; reverse engeniering (alas!) says
insert strTextToInsert at iInsertAtLineNumber line of fileName file
(or add the text if the file is too short)
Then implementation:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
...
string fileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
List<String> lines = File
.ReadLines(fileName)
.ToList();
if (lines.Count > iInsertAtLineNumber)
lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
File.WriteAllLines(fileName, lines);
Please, do not use obsolete class ArrayList but List<T> (List<String> in the question). Often File.ReadLines and File.WriteAllLines are more readable and easier to maintain than StreamReader/StreamWriter.

How do I populate an array with foreach?

How do I get the data I can write in the console to write to the array and the console.
At the moment it only displays on the console (not added functionality to add to array).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
String[] arr = new String[100];
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
Console.WriteLine("Contents of Text File: ");
foreach (string line in lines)
{
Console.WriteLine("\r\t" + line);
}
System.IO.File.WriteAllLines(#"C:\Test.txt",lines);
Console.WriteLine("Press any key to Exit");
Console.ReadKey();
}
}
}
if my lines of text say
hello
my
name
is
Simon
then the first 5 slots of the array should contain each line?
The line:
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
is already creating an array, each element of which contains one line.
There is no need to populate a new array with this same information via a foreach.
If you want to copy the lines from the text file into another array, then you can do this:
String[] arr = new String[lines.Length];
Array.Copy(lines, arr, lines.Length);
found a work around. the path i was going down was too complicated. thanks for all your input
fixed code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
string fileName = #"C:shpereCompare3.txt";
List<string> Names = new List<string>();
List<string> Value = new List<string>();
using (StreamReader fileReader = new StreamReader(fileName))
{
string fileLine;
while (!fileReader.EndOfStream)
{
fileLine = fileReader.ReadLine();
if (fileLine.StartsWith("Name"))
{
Names.Add(fileLine.Substring(21));
}
if (fileLine.StartsWith("Center"))
{
string[] fileSplit = fileLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Value.Add(fileSplit[1]);
}
}
string outputString = "";
for (int i = 0;i < Names.Count; i++)
{
outputString += Names[i] + " = " + Value[i] + "\r\n";
}
System.IO.File.WriteAllText(#"C:Test.txt", outputString);
}
}
}
}

Open a txt file using C# and read the numbers on the file

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Example:
Now what I want to do is to search (for 1 2 9 ) and send to the console.
I have tried a lot of code but nothing seems to work :(
This is my current code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Padroes
{
class Program
{
static void Main(string[] args)
{
try
{
// Open the text file using a stream reader.
const string FILENAME = #"Example.txt";
List<List<int>> data = new List<List<int>>();
string inputLine = "";
StreamReader reader = new StreamReader(FILENAME);
while ((inputLine = reader.ReadLine()) != null)
{
inputLine = inputLine.Trim();
if (inputLine.Length > 0)
{
List<int> inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList();
data.Add(inputArray);
Console.WriteLine(inputLine);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
With this code this is my output:
Now what can I do to search only for ( 1 2 9 ) and send only the 1 2 9 to console ?
I belive this would do the trick.. I simply used a StreamReader and looped throught each line.. Im not sure if i got the part of the condition 100% but if i do it should look somthing like this :
StreamReader file = new StreamReader(#"test.txt");
string line= file.ReadLine();
while(line!=null)
{
if (line.Equals("5 8 1 7"))
MessageBox.Show(line);
line = file.ReadLine();
}
Goodluck.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
List<List<int>> data = new List<List<int>>();
string inputLine = "";
StreamReader reader = new StreamReader(FILENAME);
while((inputLine = reader.ReadLine()) != null)
{
inputLine = inputLine.Trim();
if (inputLine.Length > 0)
{
List<int> inputArray = inputLine.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList();
data.Add(inputArray);
}
}
}
}
}
​

The old switcheroo (switch position in file)

I would really appreciate if somebody could help me/offer advice on this.
I have a file, probably about 50000 lines long, these files are generated on a weekly basis. each line is identical in terms of type of content.
original file:
address^name^notes
but i need to perform a switch. i need to be able to switch (on each and every line) the address with the name. so after the switch has been done, the names will be first, and then addresses and then notes, like so:
result file:
name^address^notes
50,000 isn't that much these days, so simply reading in the whole file and outputting the wanted format should work fine for you:
string[] lines = File.ReadAllLines(fileName);
string newLine = string.Empty;
foreach (string line in lines)
{
string[] items = line.Split(myItemDelimiter);
newLine = string.Format("{0},{1},{2}", items[1], items[0], items[2]);
// Append to new file here...
}
How about this?
StreamWriter sw = new StreamWriter("c:\\output.txt");
StreamReader sr = new StreamReader("c:\\input.txt");
string inputLine = "";
while ((inputLine = sr.ReadLine()) != null)
{
String[] values = null;
values = inputLine.Split('^');
sw.WriteLine("{0}^{1}^{2}", values[1], values[0], values[2]);
}
sr.Close();
sw.Close();
Go go gadget REGEX!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static string Switcheroo(string input)
{
return System.Text.RegularExpressions.Regex.Replace
(input,
#"^([^^]+)\^([^^]+)\^(.+)$",
"$2^$1^$3",
System.Text.RegularExpressions.RegexOptions.Multiline);
}
static void Main(string[] args)
{
string input = "address 1^name 1^notes1\n" +
"another address^another name^more notes\n" +
"last address^last name^last set of notes";
string output = Switcheroo(input);
Console.WriteLine(output);
Console.ReadKey(true);
}
}
}

Categories

Resources