File method with removing lines - c#

I am working on a method that reads txt file with multiple lines and then turns it into a txt file with only single line.
Like this:
first line,
second line,
third line.
Into this:
first line, second line, third line.
I have this code but it only shows "third line." in file:
MAIN:
static void Main(string[] args)
{
string fLine= "first line,\n second line,\n third line.";
string sLine= "";
Console.Write(fLine);
Console.WriteLine();
Console.Write(sLine);
string filDat1 = "D:\\Dat1.txt";
string filDat2 = "D:\\Dat2.txt";
if (File.Exists(filDat1))
Console.WriteLine("File already exist!");
else
{
File.WriteAllText(filDat1, fLine);
}
File.WriteAllText(filDat2, sLine);
changeFile(filDat1);
Console.ReadKey();
}
METHOD:
public static void changeFile(string name)
{
StringBuilder dato;
string filDat2 = "D:\\Dat2.txt";
try
{
string[] lines = File.ReadAllLines(name);
foreach (string line in lines)
{
Console.WriteLine("Words in file: " + line);
}
Console.WriteLine();
Console.Write("New words in new file: ");
foreach (string line in lines)
{
string line1 = line;
dato = new StringBuilder();
line1 = line1.Replace("\n", " ");
for (int i = 0; i < line1.Count(); i++)
{
if (!line1[i].Equals(""))
{
dato.Append(line1[i] + "");
}
}
Console.WriteLine(dato);
File.WriteAllText(filDat2, dato.ToString());
}
}
I don't know what I'm doing wrong. I only get the last word in my case "third word." in new file Dat2.txt.
Also, is there any way to create a method that can take two files. One file to read and one file to write that changed text to it?

Here is a method to make anew file for given file with only 1 line:
public static void changeFile(string InputPath,string OutputPath)
{
List<string> OUTPUT = new List<string>();
StreamReader sr = new StreamReader(InputPath);
while (!sr.EndOfStream)
{
OUTPUT.Add(sr.ReadLine());
}
sr.Close();
StreamWriter fs = new StreamWriter(OutputPath);
string output = "";
foreach (string line in OUTPUT)
{
output += line + " ";
}
fs.WriteLine(output);
fs.Close();
}

In case you were curious as to why your approach didn't work, it was because you reset dato every iteration, just move that outside and away you go, I've also moved the write outside too since you only need to do that once.
dato = new StringBuilder();
foreach (string line in lines)
{
string line1 = line;
line1 = line1.Replace("\n", " ");
for (int i = 0; i < line1.Count(); i++)
{
if (!line1[i].Equals(""))
{
dato.Append(line1[i] + "");
}
}
Console.WriteLine(dato);
}
File.WriteAllText(filDat2, dato.ToString());

Related

Is there a more efficient way of reading and writing a text fill at the same time?

I'm back at it again with another question, this time with regards to editing text files. My home work is as follow
Write a program that reads the contents of a text file and inserts the line numbers at the beginning of each line, then rewrites the file contents.
This is what I have so far, though I am not so sure if this is the most efficient way of doing it. I've only started learning on handling text files at the moment.
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
StreamReader reader = new StreamReader(fileName);
int lineCounter = 0;
List<string> list = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
list.Add("line " + (lineCounter + 1) + ": " + line);
line = reader.ReadLine();
lineCounter++;
}
}
StreamWriter writer = new StreamWriter(fileName);
using (writer)
{
foreach (string line in list)
{
writer.WriteLine(line);
}
}
}
your help would be appreciated!
thanks once again. :]
this should be enough (in case the file is relatively small):
using System.IO;
(...)
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i< lines.Length; i++)
{
lines[i] = string.Format("{0} {1}", i + 1, lines[i]);
}
File.WriteAllLines(fileName, lines);
}
I suggest using Linq, use File.ReadLinesto read the content.
// Read all lines and apply format
var formatteLines = File
.ReadLines("filepath") // read lines
.Select((line, i) => string.Format("line {0} :{1} ", line, i+1)); // format each line.
// write formatted lines to either to the new file or override previous file.
File.WriteAllLines("outputfilepath", formatteLines);
Just one loop here. I think it will be efficient.
class Program
{
public static void Main()
{
string path = Directory.GetCurrentDirectory() + #"\MyText.txt";
StreamReader sr1 = File.OpenText(path);
string s = "";
int counter = 1;
StringBuilder sb = new StringBuilder();
while ((s = sr1.ReadLine()) != null)
{
var lineOutput = counter++ + " " + s;
Console.WriteLine(lineOutput);
sb.Append(lineOutput);
}
sr1.Close();
Console.WriteLine();
StreamWriter sw1 = File.AppendText(path);
sw1.Write(sb);
sw1.Close();
}

Replacing a certain word in a text file

I know this has been asked a few times, but I have seen a lot of regex etc., and I'm sure there is another way to do this with just a stream reader/writer. Below is my code. I'm trying to replace "tea" with the word "cabbage". Can somebody help? I believe I have the wrong syntax.
namespace Week_9_Exer_4
{
class TextImportEdit
{
public void EditorialControl()
{
string fileName;
string lineReadFromFile;
Console.WriteLine("");
// Ask for the name of the file to be read
Console.Write("Which file do you wish to read? ");
fileName = Console.ReadLine();
Console.WriteLine("");
// Open the file for reading
StreamReader fileReader = new StreamReader("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
// Read the lines from the file and display them
// until a null is returned (indicating end of file)
lineReadFromFile = fileReader.ReadLine();
Console.WriteLine("Please enter the word you wish to edit out: ");
string editWord = Console.ReadLine();
while (lineReadFromFile != null)
{
Console.WriteLine(lineReadFromFile);
lineReadFromFile = fileReader.ReadLine();
}
String text = File.ReadAllText("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
fileReader.Close();
StreamWriter fileWriter = new StreamWriter("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt", false);
string newText = text.Replace("tea", "cabbage");
fileWriter.WriteLine(newText);
fileWriter.Close();
}
}
}
If you don't care about memory usage:
string fileName = #"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));
If you have a multi-line file that doesn't randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:
// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
// Create a temporary file path where we can write modify lines
string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
// Open a stream for the temporary file
using (var tempFileStream = new StreamWriter(tempFile))
{
string line;
// read lines while the file has them
while ((line = sourceFile.ReadLine()) != null)
{
// Do the word replacement
line = line.Replace("tea", "cabbage");
// Write the modified line to the new file
tempFileStream.WriteLine(line);
}
}
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);
In the end i used this : Hope it can help out others
public List<string> EditorialResponse(string fileName, string searchString, string replacementString)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Replace(searchString, replacementString);
list.Add(line);
Console.WriteLine(line);
}
reader.Close();
}
return list;
}
}
class Program
{
static void Main(string[] args)
{
TextImportEdit tie = new TextImportEdit();
List<string> ls = tie.EditorialResponse(#"C:\Users\Tom\Documents\Visual Studio 2013\story.txt", "tea", "cockrel");
StreamWriter writer = new StreamWriter(#"C:\Users\Tom\Documents\Visual Studio 2013\story12.txt");
foreach (string line in ls)
{
writer.WriteLine(line);
}
writer.Close();
}
}
}

Why isn't there newline on this file write?

I have written some code to compare 2 files and write their common lines to a 3rd file. For some reason though the 3rd file which contains the common lines has ALL the common lines written to it on 1 line. This should really be 1 new line per common line..I have even tried adding Console.WriteLine('\n'); to add a new line to separate the common lines but this isn't helping. Any ideas as to what is wrong?
//This program will read files and compares to see if they have a line in common
//if there is a line in common then it writes than common line to a new file
static void Main(string[] args)
{
int counter = 0;
string line;
string sline;
string[] words;
string[] samacc = new string[280];
//first file to compare
System.IO.StreamReader sfile =
new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\userlist.txt");
while ((sline = sfile.ReadLine()) != null)
{
samacc[counter] = sline;
Console.WriteLine();
counter++;
}
sfile.Close();
//file to write common lines to.
System.IO.StreamWriter wfile = new System.IO.StreamWriter("C:\\Desktop\\autoit\\New folder\\KenUserList.txt");
counter = 0;
//second file to compare
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\AllUserHomeDirectories.txt");
while ((line = file.ReadLine()) != null)
{
words = line.Split('\t');
foreach (string i in samacc)
{
if (words[0] == i)
{
foreach (string x in words)
{
wfile.Write(x);
wfile.Write('\t');
}
Console.WriteLine('\n');
}
}
}
file.Close();
wfile.Close();
// Suspend the screen.
Console.ReadLine();
}
Change Console.WriteLine('\n'); to wfile.WriteLine('\n');
You can do this in a much better way:
var file1 = File.ReadLines(#"path1");
var file2 = File.ReadLines(#"path2");
var common = file1.Intersect(file2); //returns all lines common to both files
File.WriteAllLines("path3", common);

Logical error in writing data in a text file in one column

My Usecase is to read data from a textfile by browsing to the location of the file containing the data to be quoted.the data from the file is save in a list. i use arraylist to get the data and loop through the arraylist and concatenate each string then create output file to store the data in single column as demostrated below
Example of a string:
20050000
40223120
40006523
sample out put:
'20050000',
'40223120',
'40006523'
But my code is currently displaying the output in the format:
'20050000'20050000,
'40223120'20050000,
'40006523'40006523
Pls help.
public List<string> list()
{
List<string> Get_Receiptlist = new List<string>();
String ReceiptNo;
openFileDialog1.ShowDialog();
string name_of_Textfile = openFileDialog1.FileName;
try
{
StreamReader sr = new StreamReader(name_of_Textfile);
{
while ((ReceiptNo = sr.ReadLine()) != null)
{
Get_Receiptlist.Add(ReceiptNo);
} // end while
MessageBox.Show("Record saved in the Data list");// just for testing purpose.
}// end StreamReader
}
catch (Exception err)
{
MessageBox.Show("Cannot read data from file");
}
return Get_Receiptlist;
}
private void button2_Click(object sender, EventArgs e)
{
string single_quotation = "'";
string comma = ",";
string paths = #"C:\Users\sample\Desktop\FileStream\Output.txt";
if (!File.Exists(paths))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(paths))
{
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
sw.Close();
MessageBox.Show("Finish processing File");
}//end using
}// end if
}
In your method button2_Click you have bad loop:
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
First I'm not even sure its Java ... but if it was Java, then I would replace this fragment with this:
List<String> values = list();
for (int i = 0; i < values.size(); i++)
{
String rec = values.get(i);
StringBuilder quoted_receipt = new StringBuilder();
if (i > 0)
{
// add comma only if the first iteration already passed
quoted_receipt.append(comma);
}
quoted_receipt.append(single_quotation).append(rec).append(single_quotation);
sw.WriteLine(quoted_receipt.toString());
sw.WriteLine(Environment.NewLine);
}

How to give a file path in code instead of command line

I've been working on my module exercises and I came across this code snippet which reads the text file and prints the details about it.
It's working fine, but I just want to know how to give the path of the text file in the code itself other than giving the path in the command line.
Below is my code.
class Module06
{
public static void Exercise01(string[] args)
{
string fileName = args[0];
FileStream stream = new FileStream(fileName, FileMode.Open);
StreamReader reader = new StreamReader(stream);
int size = (int)stream.Length;
char[] contents = new char[size];
for (int i = 0; i < size; i++)
{
contents[i] = (char)reader.Read();
}
reader.Close();
Summarize(contents);
}
static void Summarize(char[] contents)
{
int vowels = 0, consonants = 0, lines = 0;
foreach (char current in contents)
{
if (Char.IsLetter(current))
{
if ("AEIOUaeiou".IndexOf(current) != -1)
{
vowels++;
}
else
{
consonants++;
}
}
else if (current == '\n')
{
lines++;
}
}
Console.WriteLine("Total no of characters: {0}", contents.Length);
Console.WriteLine("Total no of vowels : {0}", vowels);
Console.WriteLine("Total no of consonants: {0}", consonants);
Console.WriteLine("Total no of lines : {0}", lines);
}
}
In your static void Main, call
string[] args = {"filename.txt"};
Module06.Exercise01(args);
Reading of a text file is much easier with File.ReadAllText then you don't need to think about closing the file you just use it. It accepts file name as parameter.
string fileContent = File.ReadAllText("path to my file");
string fileName = #"path\to\file.txt";

Categories