Appendtext not working - c#

So I'm trying to make a program that calculates and saves your BMI into a file.
I tried using appendtext like this.
StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt");
logboekBSA.Close();
logboekBMI = File.AppendText(path + "Logbmi.txt");
logboekBMI.WriteLine("BMI: " + bmi.getBMI());
logboekBMI.Close();
And I read the file to a text box like this:
StreamReader logbmi = new StreamReader(path + "Logbmi.txt");
txtLogboek.Text = logbmi.ReadToEnd();
It deletes the line that was already in the file and inserts the new one. It never appends.

If I understand the question correctly, you want to write text to a file without overwriting any text that is already there.
In that case, you need to define your StreamWriter like so:
StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt", true);
The true parameter means that you want to append text to the file. Without it, you are overwriting the file every time you create a new StreamWriter.

Your code seems over complicated for what you want to do. You only need two lines of code, one to save the text and one to read it.
Save text: File.AppendAllText
Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
File.AppendAllText("C:\path\to\file\Logbmi.txt", "The BMI to add");
Read text: File.ReadAllText
Opens a text file, reads all lines of the file into a string, and then closes the file.
txtLogboek.Text = File.ReadAllText("C:\path\to\file\Logbmi.txt");

Related

.NET Core 2.2 Razor Page Code Behind Creates Text File, But Fails to Write Simple Line To File

Not sure what I am doing wrong. I can create a text file named using Now date and time. My writing to the file fails. If I don't put ".Close()" at the end of the CreateText, it says the file is open by another process when trying to write. With the ".Close()" there are no errors but it doesn't write.
var newFileName = "logs\\" + DateTime.Now.ToString().Replace("/","_").Replace(":","-").Replace(" ","__") + ".txt";
var webRootPath = _environment.WebRootPath;
var dataPath = Path.Combine(webRootPath, newFileName);
System.IO.File.CreateText(dataPath).Close();
System.IO.File.AppendText(dataPath).WriteLine("this is before save");
Just use this:
//System.IO.File.CreateText(dataPath).Close();
System.IO.File.AppendText(dataPath).WriteLine("this is before save");
CreateText() will create a new empty file each time.
AppendText() will create the file if necessary.
But you are leaking file handles here. Appendtext returns a TextWriter that needs to be closed.
Instead of fixing that, consider using a reliable logging packages.

Program crashing due to IOException

I'm new to C# and I'm trying to create a simple program that asks the user to input a filename and some text to then be saved to the newly created file. Maybe I went too fast and did not learn everything I should have about file manipulation. Any help would be appreciated.
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = folderPath + fileName;
File.Create(filePath);
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
var inputTextUser = Console.ReadLine();
File.AppendAllText(filePath, inputTextUser);
When the application crashes on line 29, I get this message:
System.IO.IOException the process cannot access the file because it is being used by another process.
Line 29 which is the AppendAllText line.
The problem here is that you (your application) still "hold" that file. Actualy, you don't need to create that file, before you write something to it. As stated here AppendAllText will create a file, if it does not exists, so just remove that line, where File.Create(filePath);
You need to close/dispose the previous stream that accessed the file because File.Create keeps the file open and returns a FileStream object.
I checked your code and this solution works.
File.Create(filePath).Close();
OR/AND
File.Create(filePath).Dispose();
Rewrite your code like as
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = folderPath + fileName;
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
string[] lines = new string[1];
var inputTextUser = Console.ReadLine();
lines[0] = inputTextUser;
//File.AppendAllText(filePath, inputTextUser);
File.WriteAllLines(filePath, lines);
You can write without array
File.WriteAllText(filePath, inputTextUser);
The issue is that the File.Create method keeps the file opened thus the Operating System puts a lock on it. The method returns a FileStream object you can use for read/write access. Before you can write to that file with a different method (such as File.WriteAllText - this method will try to open an already opened file), the FileStream object must be first disposed. See this MS reference.
Simply commenting out that line of code will fix the IOException.
In general, File.Create is not a very commonly used method and is generally used in more specialized cases. If possible, the prefered way is to construct your text file in memory using a string or a StringBuilder then output the contents to file. In your case, that is definitely the approach you want to take. As others have mentioned, you would use File.WriteAllText. It will create the file if it does not exist, or replace the contents of the already existing file. If you want to keep previous content, the use File.AppendAllText as you did in your question. This method will create the file if it does not exist or append the text to the end of the previous content.
Try this:
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = System.IO.Path.Combine(folderPath, fileName);
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, "");
}
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
var inputTextUser = Console.ReadLine();
File.AppendAllText(filePath, inputTextUser);
That'll stop the File.Create holding the file open with the OS.

Create text file in asp.net using code

How do I create a text file using ASP.Net? I tried using Streamwriter but it only writes to exist file:
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), false))
{
_testData.WriteLine(txtText.Text); // Write the file.
_testData.WriteLine(txtLink.Text); // Write the file.
}
So how do I create it. I have tried:
FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]]);
but it did not work.
string FilePath = Server.MapPath("FILENAME.txt");
string FileContent = "Put File Content Here";
File.WriteAllText(FilePath, FileContent);
The constructor creates the file for you if it doesn't exist, so you shouldn't have to change anything. Just be aware that specifying "false" in the constructor will overwrite the file each time this code is executed.
Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
https://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx

How do I create an already populated text file?

I want to create a text file with the extension .jrq and populate it with two lines. However I want this to happen "all at once" instead of creating the text file and then adding the two lines. Basically I need to create an already populated text file.
Here is my current code:
FileStream fileStream = new FileStream(folder + filename + ".jrq", FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine("Line1");
streamWriter.WriteLine("Line2");
streamWriter.Flush();
streamWriter.Close();
The reason I need the file creation and the file appending to happen together is because I have a windows service that scans the folder that this text file will be created in and that service triggers a job the second it sees a .jrq file (and does logic based on what's written in the file). It notices the .jrq file before I've written anything in it and throws an error.
I think you are better off using a small trick. As adv12 pointed out writing all at once with one single method does not guarantee the implementation is atomic. if I were you I would create a temporary file:
FileStream fileStream = new FileStream(folder + filename + ".tmp",
FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine("Line1");
streamWriter.WriteLine("Line2");
streamWriter.Flush();
streamWriter.Close();
and then rename it using File.Move:
System.IO.File.Move(folder + filename + ".tmp",folder + filename + ".jrq");
So the job will start when the file jrq is full of data. it's not a super elegant solution but it would work.
Hope it helps.
You could write the file with a different filename, then move it once you've populated it. According to this question, file moves are atomic within NTFS, so your service would never see a half-written file.
File.WriteAllText is what you're looking for. If the file does not exist, it will create it with the text in it on creation.

Script task inside a SSIS For Each loop - writing to a file

My script task is inside a SSIS for each loop. I want the script task to write some dynamic string to one file only for all iterations. After every iteration, the file should get appended, not overwritten with the current value of the dynamic string. Its like a logging "tool". Btw, SSIS is SQL server integration services, an ETL tool.
How do I do this ?
I tried using a script, but it seems to be overwriting the file with the dynamic string. I don't want that. I want it to be appended to the file instead.
Here is the script which is inside my for each loop -
String text = "My text here";
String path = #"C:\Data\TextFiles\logFile.txt";
StreamWriter file = new StreamWriter(path, true);
file.WriteLine(text);
file.Close();
It seems like a much easier approach is to use File.AppendAllText(), or one of the other variations in System.IO.File.
string text = "My text here";
string path = #"C:\Data\TextFiles\logFile.txt";
System.IO.File.AppendAllText(path, text);
From the MSDN:
Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

Categories

Resources