c# StreamWriter.WriteLine("string") not writing anything - c#

So I File.Create a txt and then try to write a line on it like so:
StreamWriter.WriteLine("string");
but it just skips right past it like the line doesn't exist without any messages, warnings, or errors.

This is how to use streamwriter.
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", false))
{
writetext.WriteLine("Header");
}
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", true))
{
foreach (var data in _data)
{
writetext.WriteLine("Sample");
}
}
Notice the boolean (true or false) in the second parameter of StreamWriter class
new StreamWriter("C:\\sample.txt", true)
True: Append in file if exists
False: Overwrite file if exists

this is a bit of a long answer and example. But when I am writing commands to my digital assistant this is how I use StreamWriter.
StreamWriter sw;
StreamReader sr;
then in the code you do this
Settings.Default.ShellC = #"C:\Users\" + userName + "\\Documents\\Alexis Custom Commands\\Shell Commands.txt";
scpath = Settings.Default.ShellC;
if (!File.Exists(scpath))
{ sw = File.CreateText(scpath); sw.Write("My Documents"); sw.Close(); }
the textbox is the ShellC design name. you would add that to your properties then, in your using statements add the properties. then if you wanted to read them back then you would use
StreamReader
and then ference the file as
ArrayShellCommands = File.ReadAllLines(scpath);

Related

Creating a Txt-File and write to it [duplicate]

This question already has answers here:
C# exception. File is being used by another process
(7 answers)
Closed 5 years ago.
I want to create a text file then add the text of a TextBox to it.
Creating the text file works without any problems with following code:
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
File.Create(path);
}
But I get an error that the file is being used when I try to add the text to the text file. If the file already exist before it run the code I don't get this error and the TextBox.Text is added to the File.
I use this code to add the text to the text file:
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
}
Can you help me?
You don't actually have to check if the file exists, as StreamWriter will do that for you.
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
public StreamWriter(
string path,
bool append
)
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
You should use File.Create with using statement as it's locking the file on creating.So just change this line :
File.Create(path);
To this:
using (File.Create(path));
As you can see here, StreamWriter will actually create a file on specified path when it doesn't exist so it's useless to check for it.
I would suggest to remove the part which is creating the file and simply just start writing :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
But if you really want to create the file beforehand, remember to Dispose FileStream object created by File.Create call. Dispose call will automatically call Flush and Close for you so it's safe enough and you can do this in many ways like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
using ( File.Create(path) ) ; // This will generate warnings that you're not using the object and so on, but that's okay,
}
Or like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Dispose();
}
If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. So you don't need to check if the file exists or not.
You need to make sure the file is closed before you want to modify it.
You need to Move your
tw.Close();
Outside your using. Like so :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
tw.Close();
}
}
Edit : As pointed out, when the using ends the writer is disposed, so does not need manually closing.
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
}
}
This problem has been answered before in this thread.
Closing a file after File.Create
You will need to close the stream to the file before using it again.

Create and write file txt

How can I create and then modify writing on this file?
string fileName = #"C:\...\MioFile.txt";
In main:
File.CreateText(fileName);
Then when I would edit the file by adding text.
StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();
But the file is empty and I cannot write anything.
I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".
Use File.AppendAllText instead of StreamWriter. Its simple:
File.AppendAllText(filename, "Hello"+variable);
You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.
I like to use the "using" statements:
//full path
var fileName = #"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
//pass the fileStream into the writer.
using (var writer = new StreamWriter(fileStream))
{
writer.WriteLine("{0} => file appended", DateTime.Now);
}//dispose writer
}//dispose fileStream

"File in use" error when writing to text file

I'm getting the error The process cannot access the file 'C:\Users\Ryan\Desktop\New folder\POSData.txt' because it is being used by another process. when I try to create a file and then write to it. What process is using the file?? I checked for a file.close to call after I create the file, but it doesn't exist. How do I get past this? Thanks!
Heres my code:
MessageBox.Show("Please select a folder to save your database to.");
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
if (!File.Exists(databasePath + "\\POSData.txt"))
{
File.Create(databasePath + "\\POSData.txt");
}
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Edit: Only happens when creating the file. If it already exists, no error occurs.
Actually, don't even bother using File.Create. The reason you're getting that error is because File.Create is opening up a stream on that text file.
string filePath = "databasePath + "\\POSData.txt"";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
You are keeping the file open when you call File.Create (i.e. you never close the file).
StreamWriter will create the file for you if it doesn't exist, so I wouldn't bother checking yourself. You could just remove the code that checks whether it exists and creates it if it doesn't.
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Note that if the file doesn't exist, the second bool parameter in the StreamWriter constructor is ignored.
File.Create also opens the file for reading/writing. As such, you're leaving an open FileStream when you File.Create.
Assuming that overwriting is OK, then you probably want to do something like this:
using (var fs = File.Create(databasePath + "\\POSData.txt"))
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine(stockCount);
}
given that File.Create:
Creates or overwrites a file in the specified path.
The File.Create returns a FileStream object that might need to be closed.
The FileStream object created by this method has a default FileShare
value of None; no other process or code can access the created file
until the original file handle is closed.
using (FileStream fs = File.Create(databasePath + "\\POSData.txt"))
{
fs.Write(uniEncoding.GetBytes(stockCount), 0, uniEncoding.GetByteCount(stockCount));
}
I used this and it worked
`File.AppendAllText(fileName,"");`
This creates a new file, writes nothing to it, then closes it for you.

Writing data from textbox into text file

Here is the code im using to write and read from text file.
StreamWriter sw1 = new StreamWriter("DataNames.txt");
sw1.WriteLine(textBox1.Text);
sw1.Close();
StreamWriter sw2 = new StreamWriter("DataNumbers.txt");
sw2.WriteLine(textBox2.Text);
sw2.Close();
FileInfo file1 = new FileInfo("DataNames.txt");
StreamReader sr1 = file1.OpenText();
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
The thing is that when I click my button to save data from my textboxes to my text files an error appears that says "The process cannot access the file 'C:\xxxx\xxxxxx\xxxxx\xxxx\xxxxx\xxxxx.txt' because it is being used by another process."
Can anyone tell me why I have this error and maybe help me fix it
Try added a using statment around your streams to make sure they are Disposed otherwise the file is still locked to the stream
Example:
//Write
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
// Read
foreach (var line in File.ReadAllLines("DataNames.txt"))
{
listBox1.Items.Add(line);
}
foreach (var line in File.ReadAllLines("DataNumbers.txt"))
{
listBox2.Items.Add(line);
}
It appears you do not close the file after you read it. After you call FileInfo.OpenText you get a StreamReader which has to be closed, either via Close method, or even better, with a using statement.
But there are already methods that do all that for you, have a look at File.WriteAllText,
File.AppendAllText and File.ReadAllLines methods.
You need to Close the StreamReader object once you do not need it any more. This should fix this issue.
I.e.
StreamReader sr1 = file1.OpenText();
try {
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
}
finally {
sr1.Close();
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
try {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
finally {
sr2.Close();
}
You have opened files but not closed.
StreamReader sr1 = file1.OpenText();
StreamReader sr2 = file2.OpenText();
Your problem occurs, because you are not closing the stream readers.
A safer way of using external resources (the files in this case) is to embed their use in a using statement. The using statement automatically closes the resource at the end of the statement block or if the statement block if left in another way. This could be a return statement or an exception, for instance. It is guaranteed that the resource will be closed, even after an exception occurs.
You can apply the using statement on any object which implements the IDisposable interface.
// Writing to the files
using (var sw1 = new StreamWriter("DataNames.txt")) {
sw1.WriteLine(textBox1.Text);
}
using(var sw2 = new StreamWriter("DataNumbers.txt")) {
sw2.WriteLine(textBox2.Text);
}
// Reading from the files
FileInfo file1 = new FileInfo("DataNames.txt");
using (StreamReader sr1 = file1.OpenText()) {
while (!sr1.EndOfStream) {
listBox1.Items.Add(sr1.ReadLine());
}
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
using (StreamReader sr2 = file2.OpenText()) {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
However, you can simplify the reading part like this
// Reading from the files
listBox1.Items.AddRange(File.ReadAllLines("DataNames.txt"));
listBox2.Items.AddRange(File.ReadAllLines("DataNumbers.txt"));
I've seen this behavior before - usually there's another process open that's blocking the file access. Do you have multiple development servers open in your taskbar? (Strange, yes, but I've seen it happen)

StreamWriter is not able to write in file

My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info

Categories