This question already has answers here:
Write List<KeyValuePair<string, List<string>>> to text file?
(3 answers)
How can I write the values in a List to a text file?
(2 answers)
Writing List<String> contents to text file after deleting string
(3 answers)
Closed 3 years ago.
I´m currently trying to improve my c# skills and want to make a check-in system for workers. I want to save the timestamps in a text file and add every new stamp in the same personal .txt file.
My problem is not making it work, my problem is when I write out my list the line System.Collections.Generic.List1[System.String]` is added for every text I add. Please Help me solve this problem.
I don´t really know how to get rid of the System.Collections.Generic.List1[System.String]` part
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Provar_på_IO_File_system
{
class Program
{
static void Main(string[] args)
{
string workerName = "Albert Einstien";
string date = "2019-10-17";
string time = "14.29";
if (File.Exists(workerName + ".txt"))
{
string line;
StreamReader sr = new StreamReader(workerName + ".txt");
List<string> readLines = new List<string>();
line = sr.ReadLine();
while (line != null)
{
readLines.Add(line);
line = sr.ReadLine();
}
sr.Close();
using (StreamWriter sw = File.AppendText(workerName + ".txt"))
{
sw.WriteLine(readLines);
sw.WriteLine("HELLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOO");
sw.Close();
}
}
else
{
FileStream fs = new FileStream(workerName + ".txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(date + "\t" + time + "\t" + workerName);
sw.Close();
fs.Close();
}
}
}
}
So the result I'm planning to get from this is to see if just that worker has a text file. If it has none it will create a personal file for that person and add the timestamps for him. Otherwise, if the file already, exists (he have already check-in at least once) the program will read the .txt file, save every line into a list and after that write everything that stod in the file when the system opened it but also add the new timestamp.
Everything works as I like but it doesn't only add the timestamp, the program adds the line System.Collections.Generic.List1[System.String]" and then the timestamps.
You would need to loop through the List readLines.
var fileName = string.Format("{0}.txt", workerName)
using (StreamWriter sw = File.AppendText(fileName)) {
foreach(string line in readLines) {
sw.WriteLine(line);
}
}
Related
This question already has answers here:
How to find and replace text in a file
(7 answers)
Closed 4 years ago.
The code I'm trying to write is to replace a string of words within a text file. Though I'm able to read the file's content to console, I'm unable to replace the string of words and write a new string to the file.
Here's my code:
private static void filesys_created (object sender, FileSystemEventArgs e)
{
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
File.ReadAllText(e.FullPath);
sr.Close();
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
string text = e.FullPath.Replace("The words I want to replace");
string newtext = "text I want it to be replaced with";
sw.Write(e.FullPath, text);
sw.Write(newtext);
sw.Close();
}
}
The problem is that the .Replace is deleting everything in the text file and only inserting the path of the directory.
Well, the problems as I see it are a) you're reading the file but not assigning the text to a variable b) you're not actually doing a replace and c) you are indeed writing the file name to the output.
You don't need to use streams so your code can be simplified to this:
var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
It looks like you're using a FileSystemWatcher to pick up the file, so just noting that this will fire (at least) a Changed event.
You are writing the FullPath into the file, try this:
var text = null;
using (StreamReader sr = new StreamReader(e.FullPath))
{
text = sr.ReadToEnd();
Console.WriteLine(text);
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
var replaced = text.Replace("The words I want to replace", "text I want it to be replaced with");
sw.Write(replaced);
}
This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
I have created some code which creates a txt file with an initial text, however when I try to call the method again with a new msg it does not add it to the txt file. Below is my code:
string example = "test";
WriteToLgo(example);
public static void WriteToLog(String inputtext)
{
string location= #"C:\Users\";
string NameOfFile = "test.txt";
string fileName= String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, NameOfFile);
string path= Path.Combine(location, fileName);
using (StreamWriter sr= File.CreateText(path))
{
sr.WriteLine(inputtext);
}
}
If I try and call the method a second time the new msg does not get added. Any help will be appreciated.
You should not use File.CreateText, but this StreamWriter overload instead:
//using append = true
using (StreamWriter sr = new StreamWriter(path, true))
{
sr.WriteLine(inputtext);
}
See MSDN
The File.CreateText only creates a new file each time, overwriting anything in it. Does not append to existing files.
You should use either File.AppendText(...) to open your existing file for appending content, or use the base StreamWriter class to open it with append options
Something like:
using (StreamWriter sr = File.AppendText(path))
{
sr.WriteLine(inputtext);
}
If you use the base StreamWriter class instead of File.AppendText you can use it like StreamWriter sr = new StreamWriter(path, true); HOWEVER, you must check to see if the file exists before open it for append. Probably reccomend the File.AppendText in your case.
This question already has an answer here:
No StreamReader constructor accepting a string
(1 answer)
Closed 5 years ago.
I have a problem that requires me to calculate synthetic student marks from a text file. It gives me the weights of the marks in the first row, the number of students to evaluate in the next row, and then the next rows are the students' marks. This pattern repeats through the file without major separation.
For clarity, the text file and problem are here:
I've tried making a new object with streamreader using the following code:
using (StreamReader sr = new StreamReader("DATA10.txt")) {
blahblahblah;
}
DATA10.txt is in the same folder as the program.
But I get "Cannot convert from 'string' to 'System.IO.Stream'", even though in the examples on MSDN and everywhere else use that exact code just fine. What am I doing wrong?
Eventually what I'll be doing is taking the value from the second line and using streamreader to read that amount of lines. Then repeating the whole process on the next set of data.
I really don't think it's a duplicate of that question, and the answers here are expressed in an easier to understand way.
StreamReader is suppose to take in a Stream as its parameter can also take in a Stream as a parameter and you will also have to specify the FileMode.
Instead, try something like this:
public static void Main()
{
string path = #"c:\PathToFile\DATA10.txt";
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
//blahblah
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
MSDN Reference
You must also set the "Copy to output directory" property of "DATA10.txt" in Solution Explorer to "Copy Always"
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07___ReadTextFileWhile
{
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("DATA10.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadKey();
}
}
}
I'm trying to solve this question at the moment:
Write a program that replaces every occurrence of the substring "start" with "finish" in a text file. Can you rewrite the program to replace whole words only? Does the program work for large files (e.g. 800 MB)?
I've been trying to do it but apparently you cant read and write at the same time.
If someone could look at my code and help me it would be awesome. It's throwing an exception:
The process cannot access the file 'C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt' because it is being used by another process.
You dont have to give me the answer straight but rather tell me the process. Thanks!
Here's my code at the moment
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter_15_Question_7
{
class Program
{
static void Main(string[] args)
{
StreamReader reader = new StreamReader(
#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt");
StreamWriter writer = new StreamWriter(
#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt");
using (writer)
{
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
line.Replace("start", "finish");
writer.WriteLine(line);
line = reader.ReadLine();
}
}
}
}
}
}
I've been trying to do it but apparently you cant read and write at the same time.
The trick to solving this problem is straightforward:
Open a temporary file in the same folder as the original for writing,
Read the original line-by-line, do the replacements, and write them to the temporary file
Close the original file and the temporary file
Copy temporary file in place of the original file
You are already reading your file line-by-line, so all you need to do is changing the writer to use a different file name, and adding a call to move the file after the loop is over.
Have not tested it. But this is from the links I posted in the comment.
What I would do is I'd make a temp file and write it line by line and afterwards replace the old text file with the new one.
Something like this:
string path = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt";
string pathTmp = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile-tmp.txt";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
using (StreamWriter writer = new StreamWriter(pathTmp))
{
writer.WriteLine(line.Replace("start", "finish"));
}
}
}
}
File.Delete(path);
File.Move(pathTmp, path);
StreamWriter writer = new StreamWriter(
#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt");
using (writer)
{
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
string myNewLine=line.Replace("start", "finish");
writer.WriteLine(myNewLine);
}
}
}
}
}
I think that this would be a more succinct approach:
string fileToUpdate = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt";
string tempFile = fileToUpdate + ".tmp";
File.WriteAllLines(tempFile,
File.ReadLines(fileToUpdate)
.Select(line => line.Replace("start", "finish")));
File.Delete(fileToUpdate);
File.Move(tempFile, fileToUpdate);
I'm currently working on a utility to parse multiple xml files and write the results to a csv file. On the second last line(of code) I get the error:
The process cannot access the file 'W:\SRC\hDefML\myExcelFile.csv' because it is being used by another process.'.
Can someone please help me because I have no idea what's wrong, the file isn't being used by anything else and it's driving me crazy?
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace GenNameUtility
{
class NameGenerator
{
static void Main(string[] args)
{
var files = from file in Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files") orderby file
ascending select file;
StringBuilder sb_report = new StringBuilder();
string delimiter = ",";
sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));
foreach (var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
Console.Write("The HDefML file for {0} contains these EEPROM Generators:", filename);
XDocument hdefml = XDocument.Load(file);
var GeneratorNames = from b in hdefml.Descendants("Generators") select new
{
name = (string)b.Element("GeneratorName")
}.ToString();
StringBuilder sb = new StringBuilder();
foreach (var item in GeneratorNames)
{
Console.Write(" GeneratorName is: {0}", GeneratorNames);
sb_report.AppendLine(string.Join(delimiter, filename, GeneratorNames));
var hdef = File.Create(#"W:\SRC\hDefML\myExcelFile.csv").ToString();
File.WriteAllText(hdef, sb.ToString());
}
}
Console.ReadLine();
}
}
}
You need to close the file after you have written to it. See using.
Also it would be better to open the file before the loop and close it thereafter.
The file is being used by another process... but the process is actually yours.
File.Create returns a FileStream. You're opening the file.. writing to it.. but not closing it. When the new iteration comes around.. the file is still open.
You can try something like this:
using (var file = File.Create(#"W:\SRC\hDefML\myExcelFile.csv")) {
// write content here using file
} // this closes the file automatically.
As suggested though, I would wrap the above outside of the loop, so you're not constantly opening and closing the file.
File.WriteAllText will create a file for you so there's no need to use File.Create beforehand.
File.WriteAllText(#"W:\SRC\hDefML\myExcelFile.csv", sb.ToString());
Your File.Create stream seems to be holding the lock on the file which is why File.WriteAllText is throwing the error.
If you need to use File.Create you can use a StreamWriter to write it out.
using(var fs = File.Create(#"W:\SRC\hDefML\myExcelFile.csv"))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(sb.ToString());
}
as a side note, the above using format is the same as doing
using(var fs = File.Create(#"W:\SRC\hDefML\myExcelFile.csv"))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(sb.ToString());
}
}
so you can use whichever you find more readable.