Here is the code I'm using to read from a file:
string myPath = "file.txt";
using (StreamReader sr = new StreamReader(myPath))
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
sr.Close();
}
If I place this code in Main() in the Program.cs file everything works as expected. However, I've created a custom class with a method to perform this exact code and I get red lines under myPath saying "Argument 1: cannot convert from 'string' to 'System.IO.Stream", and I get red lines under sr.Close() saying "'StreamReader' does not contain a definition for 'Close' and no accessible extension method 'Close' accepting a first argument of type 'StreamReader' could be found".
For example, my class' method is something like this...
public void ReadFile() {
string myPath = "file.txt";
using (StreamReader sr = new StreamReader(myPath)) // Red lines under myPath
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
sr.Close(); // Red lines under Close
}
}
Both Program.cs and my custom class have using System.IO; at the top as well.
Any ideas on what I'm missing?
Thanks!
UPDATE:
The whole class looks like this...
using System;
using System.IO;
namespace FileReaderLibrary
{
public class FileReader
{
public void ReadFile() {
string myPath = "file.txt";
using (StreamReader sr = new StreamReader(myPath)) // Red lines under myPath
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
sr.Close(); // Red lines under Close
}
}
}
}
Related
I have a homework assignment to create a C# console program. It should create a text file with 2 phrases:
Hello, World!
Goodbye, Cruel World!
Then I also must create a program to read the 2 phrases from the file.
After two hours this is what I have. It works, but I want to rewrite the program to be more efficient. I am mainly struggling on how to output the file into a .cs file capable of running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//structure.txt contains the program we will enter our values into.
String filePath = "Structure.txt";
WriteToFile(filePath);
}
public static void WriteToFile(string filePath)
{
//create a string array to gather our text file information.
StreamReader reader = new StreamReader(filePath);
StreamReader info = new StreamReader("Structure.txt");
StreamWriter writer = new StreamWriter("Hello.cs", true);
String temp = String.Empty;
while (!info.EndOfStream)
{
String tempstring = String.Empty;
tempstring = reader.ReadLine();
while (!reader.EndOfStream)
{
temp = reader.ReadLine();
writer.WriteLine(temp);
if (temp == "//break")
{
writer.WriteLine("String1 = {}", tempstring);
}
}
}
reader.Close();
info.Close();
writer.Close();
}
}
}
More efficient? sure
// write
string[] lines = new [] {"Hello, World!", "Goodbye, Cruel World!"};
File.WriteAllLines("c:\\myFile.txt", lines);
// read
string[] lines = File.ReadAllLines("c:\\myFile.txt");
This is all. . .
I have a text file (filename.txt) and I want to delete everything in this file from a special row number to the end of the text file.
How can I do this?
Is it even possible?
P.S.:
The number of the line is not constant.
It depends on the value of another variable in my code.
You can do the following:
Read the count of lines which you need.
Delete the file.
Write your lines to a newly created file with the same path and name.
Below is an example of the code:
using System.IO;
using System.Collections.Generic;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
int lineNumber = 4;
string filePath = #"C:\Users\Admin\Desktop\test - Copy.txt";
List<string> lines = new List<string>();
using (TextReader tr = new StreamReader(filePath))
{
int i = 0;
while(i!=lineNumber)
{
lines.Add(tr.ReadLine());
i++;
}
}
File.Delete(filePath);
File.WriteAllLines(filePath,lines);
}
}
}
I am currently trying to make an .exe in c# that I can drag and drop a .txt file onto to remove lines of text that contain the keywords "CM" and/or "Filling". It must be able to overwrite the existing data so there are no new files created. The filename is different every time except for the extension. The data is tab delimited if that has any bearing. I'm aware that there are similar questions to this but I haven't managed to adapt them to suit my needs. Also, I'm very new to this and I've been trying for about a week with no luck.
if (args.Length == 0)
return; // return if no file was dragged onto exe
string text = File.ReadAllText("*.txt");
text = text.Replace("cm", "");
string path = Path.GetDirectoryName(args[0])
+ Path.DirectorySeparatorChar
+ Path.GetFileNameWithoutExtension(args[0])
+ "_unwrapped" + Path.GetExtension(args[0]);
File.WriteAllText("*.txt", text);
\\attempt 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string concrete = "CM";
string line;
using (StreamReader reader = new StreamReader(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704.txt"))
{
using (StreamWriter writer = new StreamWriter(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704NEW.txt"))
{
while ((line = reader.ReadLine()) != null)
{
// if (String.Compare(line, yourName) == 0)
// continue;
writer.WriteLine(line.Replace(concrete, ""));
}
}
}
\\attempt 2
Thanks for your time.
Regards,
Danny
You can create a console application with the code below and then drag and drop your text file into the .exe file without opening it.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0 && File.Exists(args[0]))
{
string path = args[0];
EditFile(new List<string>() { "CM", "Filling" }, path);
}
Console.Read();
}
public static void EditFile(List<string> keyWords, string filename)
{
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(filename))
{
while (sr.Peek() >= 0)
{
lines.Add(sr.ReadLine());
}
sr.Close();
}
int removedLinesCount = 0;
bool writeline;
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (var line in lines)
{
writeline = true;
foreach (var str in keyWords)
{
if (line.Contains(str))
{
writeline = false;
removedLinesCount++;
break;
}
}
if (writeline)
sw.WriteLine(line);
}
Console.WriteLine(removedLinesCount + " lines removed from the file " + filename);
sw.Close();
}
}
}
Something like this?
using System;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
try
{
// Get the filename from the applications arguments
string filename = args[0];
// Read in all lines in the file.
var linesInFile = File.ReadLines(filename);
// Filter out the lines we don't need.
var linesToKeep = linesInFile.Where(line => !line.Contains("CM") && !line.Contains("Filling")).ToArray();
// Overwrite the file.
File.WriteAllLines(filename, linesToKeep);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
I'm trying to read and write from a txt file using C#. At the moment, I'm writing a program that reads the names in a list, shows them to the user, asks for another name, and then adds that one to the list. The reading is fine, but there's some problems with the writing.
The code compiles fine using CSC, and it executes fine, but after I type the name to add and hit enter, I get a window popping up saying
FileIO.exe has encountered a problem and needs to close.
Any idea what the problem is?
using System;
using System.IO;
public class Hello1
{
public static void Main()
{
int lines = File.ReadAllLines("Name.txt").Length;
string[] stringArray = new string[lines + 1];
StreamReader reader = new StreamReader("Name.txt");
for(int i = 1;i <=lines;i++){
stringArray[i-1] = reader.ReadLine();
}
for (int i = 1;i <=stringArray.Length;i++){
Console.WriteLine(stringArray[i-1]);
}
Console.WriteLine("Please enter a name to add to the list.");
stringArray[lines] = Console.ReadLine();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("Name.txt", true)){
writer.WriteLine(stringArray[lines]);
}
}
}
You are getting the exception because you are not closing your reader, Just place reader.Close(); after reading your file to Array.
Even better is to use using statement, since StreamReader uses IDisposable interface, this would ensure closing of the stream as well as its disposal.
string[] stringArray = new string[lines + 1];
using (StreamReader reader = new StreamReader("Name.txt"))
{
for (int i = 1; i <= lines; i++)
{
stringArray[i - 1] = reader.ReadLine();
}
}
Just a side note:
you are use File.ReadAllLines just to get Length???, you can fillup your array like:
string[] stringArray = File.ReadAllLines("Name.txt");
instead of going through StreamReader.
How about we simplify this a bit:
foreach (var line in File.ReadLines("Name.txt"))
{
Console.WriteLine(line);
}
Console.WriteLine("Please enter a name to add to the list.");
var name = Console.ReadLine();
File.AppendLine("Name.txt", name):
Now you're not dealing with the IO at all because you're leaving it to the framework by leveraging those static methods wholly.
It's good to ensure that you learn of any exceptions at the top level of a console application:
public class Hello1
{
public static void Main()
{
try
{
// whatever
}
catch (Exception ex)
{
Console.WriteLine("Exception!);
Console.WriteLine(ex.ToString());
}
finally
{
Console.Write("Press ENTER to exit: ");
Console.ReadLine();
}
}
}
This way, you'll know why the application had to close.
Additionally, you need to have your StreamReader in a using block.
If you want to read all lines from a file into an array, you can simply use:
string[] lines = File.ReadAllLines("Name.txt");
And use that array.
Use the reader.ReadToEnd function like this and don't forget to close the reader when you finish.:
StreamReader reader = new StreamReader("Name.txt");
string content = reader.ReadToEnd();
reader.Close();
The reason you get that exception is because you don't close the reader after reading. So you can't write to it without first calling the Close(); method.
You can also use the using statement instead of closing it like this:
using (StreamReader reader = new StreamReader("Name.txt")){
string content = reader.ReadToEnd();
};
Firstly, i'd just like to mention that I've only started learning C# a few days ago so my knowledge of it is limited.
I'm trying to create a program that will parse text files for certain phrases input by the user and then output them into a new text document.
At the moment, i have it the program searching the original input file and gathering the selected text input by the user, coping those lines out, creating new text files and then merging them together and also deleting them afterwards.
I'm guessing that this is not the most efficient way of creating this but i just created it and had it work in a logical manor for me to understand as a novice.
The code is as follows;
private void TextInput1()
{
using (StreamReader fileOpen = new StreamReader(txtInput.Text))
{
using (StreamWriter fileWrite = new StreamWriter(#"*DIRECTORY*\FIRSTFILE.txt"))
{
string file;
while ((file = fileOpen.ReadLine()) != null)
{
if (file.Contains(txtFind.Text))
{
fileWrite.Write(file + "\r\n");
}
}
}
}
}
private void TextInput2()
{
using (StreamReader fileOpen = new StreamReader(txtInput.Text))
{
using (StreamWriter fileWrite = new StreamWriter(#"*DIRECTORY*\SECONDFILE.txt"))
{
string file;
while ((file = fileOpen.ReadLine()) != null)
{
if (file.Contains(txtFind2.Text))
{
fileWrite.Write("\r\n" + file);
}
}
}
}
}
private static void Combination()
{
ArrayList fileArray = new ArrayList();
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
using (StreamReader reader = File.OpenText(#"*DIRECTORY*\FIRSTFILE.txt"))
{
writer.Write(reader.ReadToEnd());
}
using (StreamReader reader = File.OpenText(#"*DIRECTORY*\SECONDFILE.txt"))
{
writer.Write(reader.ReadToEnd());
}
}
}
private static void Delete()
{
if (File.Exists(#"*DIRECTORY*\FIRSTFILE.txt"))
{
File.Delete(#"*DIRECTORY*\FIRSTFILE.txt");
}
if (File.Exists(#"*DIRECTORY*\SECONDFILE.txt"))
{
File.Delete(#"*DIRECTORY*\SECONDFILE.txt");
}
}
The output file that is being created is simply outputting the first text input followed by the second. I am wondering if it is possible to be able to merge them into 1 file, 1 line at a time as it is a consecutive file meaning have the information from Input 1 followed 2 is needed rather than all of 1 then all of 2.
Thanks, Neil.
To combine the two files content in an one merged file line by line you could substitute your Combination() code with this
string[] file1 = File.ReadAllLines("*DIRECTORY*\FIRSTFILE.txt");
string[] file2 = File.ReadAllLines("*DIRECTORY*\SECONDFILE.txt");
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
int lineNum = 0;
while(lineNum < file1.Length || lineNum < file2.Length)
{
if(lineNum < file1.Length)
writer.WriteLine(file1[lineNum]);
if(lineNum < file2.Length)
writer.WriteLine(file2[lineNum]);
lineNum++;
}
}
This assumes that the two files don't contains the same number of lines.
try this method. You can receive three paths. File 1, File 2 and File output.
public void MergeFiles(string pathFile1, string pathFile2, string pathResult)
{
File.WriteAllText(pathResult, File.ReadAllText(pathFile1) + File.ReadAllText(pathFile2));
}
If the pathResult file exists, the WriteAllText method will overwrite it. Remember to include System.IO namespace.
Important: It is not recommended for large files! Use another options available on this thread.
If your input files are quite large and you run out of memory, you could also try wrapping the two readers like this:
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
using (StreamReader reader1 = File.OpenText(#"*DIRECTORY*\FIRSTFILE.txt"))
{
using (StreamReader reader2 = File.OpenText(#"*DIRECTORY*\SECONDFILE.txt"))
{
string line1 = null;
string line2 = null;
while ((line1 = reader1.ReadLine()) != null)
{
writer.WriteLine(line1);
line2 = reader2.ReadLine();
if(line2 != null)
{
writer.WriteLine(line2);
}
}
}
}
}
Still, you have to have an idea how many lines you have in your input files, but I think it gives you the general idea to proceed.
Using a FileInfo extension you could merge one or more files by doing the following:
public static class FileInfoExtensions
{
public static void MergeFiles(this FileInfo fi, string strOutputPath , params string[] filesToMerge)
{
var fiLines = File.ReadAllLines(fi.FullName).ToList();
fiLines.AddRange(filesToMerge.SelectMany(file => File.ReadAllLines(file)));
File.WriteAllLines(strOutputPath, fiLines.ToArray());
}
}
Usage
FileInfo fi = new FileInfo("input");
fi.MergeFiles("output", "File2", "File3");
I appreciate this question is almost old enough to (up)vote (itself), but for an extensible approach:
const string FileMergeDivider = "\n\n";
public void MergeFiles(string outputPath, params string[] inputPaths)
{
if (!inputPaths.Any())
throw new ArgumentException(nameof(inputPaths) + " required");
if (inputPaths.Any(string.IsNullOrWhiteSpace) || !inputPaths.All(File.Exists))
throw new ArgumentNullException(nameof(inputPaths), "contains invalid path(s)");
File.WriteAllText(outputPath, string.Join(FileMergeDivider, inputPaths.Select(File.ReadAllText)));
}