c# File1's text keeps replacing file2's when I run it - c#

All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace RandomName
{
class Program
{
static void Main(string[] args)
{
string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";
string fileName = "file1.txt";
StreamReader reader = new StreamReader(winDir + fileName);
string outputFileName = "upperfile" + fileName;
StreamWriter writer = new StreamWriter(outputFileName);
int n = 0;
string st = "";
string upperString = "";
int n2 = 0;
string st2 = "";
string upperString2 = "";
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2;
StreamWriter writer2 = new StreamWriter(outputFileName2);
do
{
++n;
st = reader.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n + ": " + st); // write to the console
writer.WriteLine(st); // write line to disk file instead, using WriteLine() method
upperString = upperString + "\n" + st; // append each line to the big string
}
while (!reader.EndOfStream);
do
{
++n2;
st2 = reader2.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n2 + ": " + st2); // write to the
console
writer2.WriteLine(st2); // write line to disk file instead,
using WriteLine() method
upperString2 = upperString2 + "\n" + st2; // append each line
to the big string
}
while (!reader2.EndOfStream);
reader.Close();
writer.Close();
Console.WriteLine("\nHere is the entire file in a string:");
Console.WriteLine(upperString);
Console.WriteLine(upperString2);
UpperString b = new UpperString(upperString);
UpperString2 c = new UpperString2(upperString2);
Console.WriteLine("\nThe string in reverse case: ");
b.showReverseCase();
Console.WriteLine("\n");
c.readingFile2();
c.toNewFile2();
}
}
}
"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.
Here is the class
class UpperString2
{
private string upperString2;
public UpperString2() { }
public UpperString2(string c) { upperString2 = c; }
public void readingFile2()
{
string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");
System.Console.WriteLine("\nAnother Poem \n");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine(line);
}
}
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!

The problem is "outputfile2" was already opened by reader2 in Main().
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
Then it raises an exception when you try to open the same file for writting in toNewFile2():
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.
Since you have moved the code to a class, call that class instead.

Related

New line in a string is not works with text file

I have a function to write a message to text file. But when passing a string with 'Environment.NewLine', it is not writes a new line to the text file. Instead it writes '\r\n'.
How to correct this? I have tried with '\n' instead of 'Environment.NewLine'. Still the new line is not coming.
The issue is happens only when passing a string with new line to the function. Like variable 'message'
string message= "First "+Environment.NewLine+" message.";
LogTheDetails(message);
public static void LogTheDetails(String message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("============================================================\n --Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND LINES
{
string testString= "testString"+ Environment.NewLine+ "WithNewLine";
File.AppendAllText(FilePath, "\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath, "\n============================================================\n");
}
}
Output
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
Expected Output:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
Below piece of code gave the output you are looking for, I tried it in .net 5 console application.
using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static string message = "First " + Environment.NewLine + " message.";
static void Main(string[] args)
{
LogTheDetails(message);
Console.WriteLine("Hello World!");
}
public static void LogTheDetails(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string currentdate = "test";
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("========================================================\n
--Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND
LINES
{
string testString = Environment.NewLine + "testString" +
Environment.NewLine + "WithNewLine";
File.AppendAllText(FilePath,
"\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath,
"\n============================================================\n");
}
}
}
}

Why this split/merge program do well in case of .txt but not in .jpg

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Homework
{
class Program
{
static void Main(string[] args)
{
string mode = args[0];
string name = args[1];
if(mode == "split")
{
FileInfo fileinfo = new FileInfo(name);
int fileSize = (int)fileinfo.Length;
int partSize = 1024;
int numberOfPart = (int)Math.Ceiling((double)fileSize / partSize);
string chunkName = "";
int byteRemaining = fileSize;
FileStream list = File.OpenWrite(name + "_list");
StreamWriter list_write = new StreamWriter(list, System.Text.Encoding.UTF8);
list_write.WriteLine(name); //list 파일 첫 줄에 원본 파일 이름 저장
Console.WriteLine(name + "_list");
for(int count = 1; count <= numberOfPart; count++)
{
byte[] buffer = new byte[partSize];
chunkName = string.Format("{0}_{1}", name, count);
int chunkSize;
FileStream origin = File.OpenRead(name);
BinaryReader origin_read = new BinaryReader(origin);
if(byteRemaining >= partSize)
{
chunkSize = partSize;
}
else
{
chunkSize = byteRemaining;
}
buffer = origin_read.ReadBytes(chunkSize); //원본 읽기
FileStream chunk = File.OpenWrite(chunkName);
BinaryWriter chunk_write = new BinaryWriter(chunk);
chunk_write.Write(buffer); //chunk에 쓰기
byteRemaining -= chunkSize;
list_write.WriteLine(chunkName); //chunkName도 list 파일에 저장
Console.WriteLine(chunkName);
origin_read.Close();
chunk_write.Close();
}
list_write.Close();
}
else if(mode == "merge")
{
FileStream list = File.OpenRead(name); //list 파일 읽는 스트림
StreamReader list_read = new StreamReader(list, Encoding.Default, true);
string originName = list_read.ReadLine();
FileStream origin = File.OpenWrite(originName); //origin 파일 다시 만드는 스트림
BinaryWriter origin_write = new BinaryWriter(origin);
int partSize = 1024;
while(list_read.EndOfStream == false) //list 파일이 끝날때까지 읽어들임
{
string chunkName = list_read.ReadLine();
byte[] buffer = new byte[partSize];
FileStream chunk = File.OpenRead(chunkName); //각 chunk 읽는 스트림
BinaryReader chunk_read = new BinaryReader(chunk);
FileInfo fileinfo = new FileInfo(chunkName);
buffer = chunk_read.ReadBytes((int)fileinfo.Length); //파일 크기만큼 buffer로 읽어옴
origin_write.Write(buffer); //buffer로 옮긴 내용 원본파일에 쓰기
}
}
Console.ReadKey();
}
}
}
*Expected
split : split file into chunks of 1kb and make [filename]_list file which contain information of name of original file name and name of chunks([filename]_1, [filename]_2 . . .)
merge : read [filename]_list file which created while split process and merge chunks one file again. And after merging, merged file have to be exactly same as original file that we split above.
*Problem
In case of .txt file -> doing well as expected, but in .jpg file, split well but merged file is not same as original file.
Issue:
The issue with your code is that when you split the file into parts/sections, instead of splitting the file into seperate files each containing the next chuck-part of bytes, you splitting the file starting each time from the begining, resulting into the wrong merging file (image demonstrating the issue)
Solution:
So what you only have to do, is just to move out of the for loop 3 specific lines of code such that your code will look like this:
FileStream origin = File.OpenRead(name); // 1st line
BinaryReader origin_read = new BinaryReader(origin); // 2nd line
for (int count = 1; count <= numberOfPart; count++)
{
...
}
origin_read.Close(); //3rd line
list_write.Close();
Recomended solution:
Although, here a recomended solution too.
using System;
using System.IO;
using System.Linq;
namespace Homework
{
class Program
{
static void Main(string[] args)
{
string mode = args[0];
string file = args[1]; // sourcefile or sourcefile_list
try{
switch (mode){
case "split":
byte[] buffer = File.ReadAllBytes(file);
int partSize = 1024;
int numberOfPart = (int)Math.Ceiling((double)buffer.Length / partSize);
string chunkPathName; // The path-and-name of the chunk-file
// go through all parts
for (int count = 0; count < numberOfPart; count++)
{
chunkPathName = file + "_" + (count + 1);
//write all bytes to the destination-chunk file from a specific point and on.... and then "pass"/write the chuck's path-name into the _list file
File.WriteAllBytes(chunkPathName, buffer.Skip(count * partSize).Take(partSize).ToArray());
File.AppendAllText(file + "_list", chunkPathName + "\n");
Console.WriteLine("Splitting: " + chunkPathName);
}
break; // exit switch
case "merge":
// create a stream pointing to your desired-destination/origin-file
var originstream = new FileStream(file.Remove(file.Length - "_list".Length, "_list".Length), FileMode.Create);
Console.WriteLine("destination path = " + file.Remove(file.Length - "_list".Length) + "\n");
// go through each line of the file (_list)
foreach (string _chunkPathName in File.ReadAllLines(file))
{
Console.WriteLine("Merging: " + _chunkPathName);
// read all bytes from chunk and append them into the origin-file
byte[] chunk = File.ReadAllBytes(_chunkPathName);
originstream.Write(chunk, 0, chunk.Length);
}
// close the stream
originstream.Close();
break; // exit switch
}
Console.WriteLine("\n" + mode + " is done!");
}catch (Exception ex){
//code for any other type of exception
}
Console.ReadKey();
}
}
}
i've tried to make it clear enough with comments too..

Convert .XYZ to .csv using c#

Hi i am using this method to replace " " to "," but is failing when i try to use it on data that have 32 millions lines. Is anyone knows how to modify it to make it running?
List<String> lines = new List<String>();
//loop through each line of file and replace " " sight to ","
using (StreamReader sr = new StreamReader(inputfile))
{
int id = 1;
int i = File.ReadAllLines(inputfile).Count();
while (sr.Peek() >= 0)
{
//Out of memory issuee
string fileLine = sr.ReadLine();
//do something with line
string ttt = fileLine.Replace(" ", ", ");
//Debug.WriteLine(ttt);
lines.Add(ttt);
//lines.Add(id++, 'ID');
}
using (StreamWriter writer = new StreamWriter(outputfile, false))
{
foreach (String line in lines)
{
writer.WriteLine(line+","+id);
id++;
}
}
}
//change extension to .csv
FileInfo f = new FileInfo(outputfile);
f.MoveTo(Path.ChangeExtension(outputfile, ".csv"));
I general i am trying to convert big .XYZ file to .csv format and add incremental field at the end. I am using c# for first time in my life to be honest :) Can you help me?
See my comment above - you could modify your reading / writing as follows :
using (StreamReader sr = new StreamReader(inputfile))
{
using (StreamWriter writer = new StreamWriter(outputfile, false))
{
int id = 1;
while (sr.Peek() >= 0)
{
string fileLine = sr.ReadLine();
//do something with line
string ttt = fileLine.Replace(" ", ", ");
writer.WriteLine(ttt + "," + id);
id++;
}
}
}

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();
}

Rewriting a text file after reading it

i got a file that is store in my appliction directory, and he got some site list.
i dont have any problem reading it, but when i want to write to it, i get
System.ArgumentException: Stream is not writeable
this is how i accsess the file:
FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate);
and this is the function that throw me the expection:
public static void WriteNewTextToFile(string text, FileStream theFile)
{
string fileText = GetAllTextFromFile(theFile);
ArrayList fileLIst = populateListFromText(fileText);
using (StreamWriter fileWriter = new StreamWriter(theFile))
{
fileWriter.Write(String.Empty);
for (int i = 0; i < fileLIst.Count; i++)
{
fileWriter.WriteLine(fileLIst[i].ToString());
}
}
}
the function read the old and new text and add it to an arry. then i clean the file from every thing, and rewriting it with the old and new data from the arry i made.
i dont know if that will help but here is the file proprites:
Build Action: None
Copy To Out Put Directory: Copy always
why i cant rewrite the file?
this is the function i use to read the file content:
public static string GetAllTextFromFile(FileStream theFile)
{
string fileText = "";
using (theFile)
{
using (StreamReader stream = new StreamReader(theFile))
{
string currentLine = "";
while ((currentLine = stream.ReadLine()) != null)
{
fileText += currentLine + "\n";
}
}
}
return fileText;
}
You have to use Read/Write file access as third parameter -
FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate, FileAccess.ReadWrite
);
Important - Remove using(theFile) statement:
public static string GetAllTextFromFile(FileStream theFile)
{
string fileText = "";
using (StreamReader stream = new StreamReader(theFile))
{
string currentLine = "";
while ((currentLine = stream.ReadLine()) != null)
{
fileText += currentLine + "\n";
}
}
return fileText;
}
Do not use using construct in your case as it will close the underlying stream as in your case you have to manually open and close stream objects.
This will allow you to write in the file as well.
For more information refer following links -
FileStream Constructor
FileAccess Enumeration

Categories