C# Output text to file on a new line - c#

I have some code which outputs data from the FileSystemWatcher class, although each times to outputs a line to test.txt, it overwrites the previous entry, is there a way to stop this happening?
Code in question:
static void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
using (StreamWriter fileWriter = new StreamWriter("test3.txt"))
{
var data = true;
fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
}
Full Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWatcherr
{
class Program
{
static void Main(string[] args)
{
string dirPath = "C:\\";
FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath);
fileWatcher.IncludeSubdirectories = true;
fileWatcher.Filter = "*.exe";
// fileWatcher.Filter = "C:\\$Recycle.Bin";
// fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
// fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
// fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
fileWatcher.EnableRaisingEvents = true;
// updated code
Console.ReadKey();
}
static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine(e.OldName + " was renamed to " + e.Name);
}
static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " was deleted");
}
static void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
using (StreamWriter fileWriter = new StreamWriter("test3.txt"))
{
var data = true;
fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
}
}
static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "");
}
}
}

Edit your code to be the below. The second parameter to the StreamWriter is if we should append or overwrite. Set to true to append and false to overwrite (default, thus your problem)
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
var data = true;
fileWriter.WriteLine(Path.Combine("C:\\", e.Name));
}
More info about this constructor can be found here http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Try
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
...
}

Replace
new StreamWriter("test3.txt")
by
new StreamWriter("test3.txt", true)
This will make the stream append to the file.

Consider opening file to append:
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
var data = true;
fileWriter.WriteLine("C:\\" + e.Name);
}
Note that it is better to use WriteLine method.

The StreamWriter class has an overload constructor that takes a second bool parameter which specifies if you want to append to an existing file. More information here.

Related

How can I nest this streamwriter within a while loop, wanting the button to be able to write infinitely

private void addTimeButton_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter(#"W:\out.txt"))
{
string[] denter code hereata = new string[4];
data[0] = fNameBox.Text;
data[1] = sNameBox.Text;
data[2] = genderCheck.Text;
data[3] = timeBox.Text;
string myStringOutput = String.Join(",", data.Select(p => p.ToString()).ToArray());
sw.Write(myStringOutput + "\n");
myStringOutput += Environment.NewLine;
sw.Close();
}
using (StreamReader sr = new StreamReader(#"W:\out.txt"))
{
while (!sr.EndOfStream)
{
readTimeButton.AppendText(sr.ReadLine());
}
}
}
I'm wanting to nest the stream writer within a while loop, similar to how to how the reader is, for some reason using the same method doesn't work. I basically want the button to be able to be pressed infinitely until the user decides they want to close the program.
First, you don't need to add an "sw.Close();" inside a using stream because the "using" will close the stream.
Why don't you include your stream writer inside a while loop like this?
private void addTimeButton_Click(object sender, EventArgs e)
{
while(true)
{
using (StreamWriter sw = new StreamWriter(#"W:\out.txt"))
{
string[] denter code hereata = new string[4];
data[0] = fNameBox.Text;
data[1] = sNameBox.Text;
data[2] = genderCheck.Text;
data[3] = timeBox.Text;
string myStringOutput = String.Join(",", data.Select(p => p.ToString()).ToArray());
sw.Write(myStringOutput + "\n");
myStringOutput += Environment.NewLine;
// sw.Close(); // not necessary whithin a using
}
using (StreamReader sr = new StreamReader(#"W:\out.txt"))
{
while (!sr.EndOfStream)
{
readTimeButton.AppendText(sr.ReadLine());
Application.DoEvents(); // to see your text increasing
}
}
}
}
The AppendText method doesn't belong to a button control.
Can you explain what you are trying to do?

Unable to store output of executed commands inside a file c# console Application

I am trying to store executed commands results inside a txt file, command execution is working fine and also showing a command prompt but I am unable to store results inside my file.
It's only creating a empty file inside that folder.
Program.cs :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace commandExecutionPractice
{
class Program
{
static void Main(string[] args)
{
var folderPath = #"C:\";
var fileName = #"\commandLog.txt";
var fullPath = folderPath + fileName;
StreamWriter writer = new StreamWriter(fullPath);
using (CmdService cmdService = new CmdService("cmd.exe"))
{
string consoleCommand = String.Empty;
do
{
Console.WriteLine("Enter Command : ");
consoleCommand = Console.ReadLine();
string output = cmdService.ExecuteCommand(consoleCommand);
writer.WriteLine(">>> {0}", output);
Console.WriteLine(">>> {0}", output);
}
while (!String.IsNullOrEmpty(consoleCommand));
}
Console.ReadLine();
}
}
}
CmdService.cs :
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace commandExecutionPractice
{
public class CmdService : IDisposable
{
private Process _cmdProcess;
private StreamWriter _streamWriter;
private AutoResetEvent _outputWaitHandle;
private string _cmdOutput;
public CmdService(string cmdPath)
{
_cmdProcess = new Process();
_outputWaitHandle = new AutoResetEvent(false);
_cmdOutput = String.Empty;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = cmdPath;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.CreateNoWindow = true;
_cmdProcess.OutputDataReceived += _cmdProcess_OutputDataReceived;
_cmdProcess.StartInfo = processStartInfo;
_cmdProcess.Start();
_streamWriter = _cmdProcess.StandardInput;
_cmdProcess.BeginOutputReadLine();
}
public string ExecuteCommand(string command)
{
_cmdOutput = String.Empty;
_streamWriter.WriteLine(command);
_streamWriter.WriteLine("echo end");
_outputWaitHandle.WaitOne();
return _cmdOutput;
}
private void _cmdProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null || e.Data == "end")
_outputWaitHandle.Set();
else
_cmdOutput += e.Data + Environment.NewLine;
}
public void Dispose()
{
_cmdProcess.Close();
_cmdProcess.Dispose();
_streamWriter.Close();
_streamWriter.Dispose();
}
}
}
Edit : I added code of CmdService class which I forgot to add.
Thanks in Advance.
It's a simple fix.
In your Main function add the line writer.Flush(); after you write to the stream as per:
writer.WriteLine(">>> {0}", output);
writer.Flush();
Alternatetively, if you wrap the streams usage in a using block, it will flush it before it closes the stream.
using (StreamWriter writer = new StreamWriter(fullPath))
{
using (CmdService cmdService = new CmdService("cmd.exe"))
{
string consoleCommand = String.Empty;
do
{
Console.WriteLine("Enter Command : ");
consoleCommand = Console.ReadLine();
string output = cmdService.ExecuteCommand(consoleCommand);
writer.WriteLine(">>> {0}", output);
Console.WriteLine(">>> {0}", output);
}
while (!String.IsNullOrEmpty(consoleCommand));
}
}

File I/O Exceptions

i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}

FIleSystemWatcher multiple folders (Dynamically)

I'm trying to use the solution found here [Create multiple instances of the same FileSystemWatcher to make FileSystemWatchers on the fly but the Watcher_Created event doesn't seem to be triggered. Any thoughts as to what I am doing wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type Enter to exit:::");
StartWatchers();
Console.ReadLine();
}
public static void StartWatchers()
{
string[] ArrayPaths = new string[2];
List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
ArrayPaths[0] = #"\\WifeyPC\c$\User\Wifey\Desktop";
ArrayPaths[1] = #"\\HubbyPC\c$\Users\Hubby\Desktop";
int i = 0;
foreach (String String in ArrayPaths)
{
watchers.Add(MyWatcherFatory(ArrayPaths[i]));
i++;
}
foreach (FileSystemWatcher watcher in watchers)
{
watcher.EnableRaisingEvents = true; ;
Console.WriteLine("Watching this folder {0}", watcher.Path);
i++;
}
}
FileSystemWatcher MyWatcherFatory(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Changed += Watcher_Created;
watcher.Path = path;
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
return watcher;
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1000);
FileInfo fileInfo = new FileInfo(e.FullPath);
Console.WriteLine("File Created!! :: {0}", e.FullPath);
}
}
}
You are never calling the StartWatchers method in your Main starting point.
Change the code as seen below:
static void Main(string[] args)
{
Console.WriteLine("Type Enter to exit:::");
StartWatchers();
Console.ReadLine();
}
You're also going to need to change your Watcher_Created method as seen below. You had the ending double quote after fullPath which would just display that entire string, when you need to place the double quote after the parameter {0}:
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1000);
FileInfo fileInfo = new FileInfo(e.FullPath);
Console.WriteLine("File Created!! :: {0}", e.FullPath);
}
You are 100% correct #scott-chamberlain. Below is the answer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type Enter to exit:::");
StartWatchers();
Console.ReadLine();
}
public static void StartWatchers()
{
string[] ArrayPaths = new string[2];
List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
ArrayPaths[0] = #"\\WifeyPC\c$\User\Wifey\Desktop";
ArrayPaths[1] = #"\\HubbyPC\c$\Users\Hubby\Desktop";top";
int i = 0;
foreach (String String in ArrayPaths)
{
watchers.Add(MyWatcherFatory(ArrayPaths[i]));
i++;
}
foreach (FileSystemWatcher watcher in watchers)
{
watcher.EnableRaisingEvents = true; ;
Console.WriteLine("Watching this folder {0}", watcher.Path);
i++;
}
}
public static FileSystemWatcher MyWatcherFatory(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Changed += Watcher_Created;
watcher.Path = path;
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
return watcher;
}
private static void Watcher_Created(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1000);
FileInfo fileInfo = new FileInfo(e.FullPath);
Console.WriteLine("File Created!! :: {0}", e.FullPath);
}
}
}

C# Help - FileSystemWatcher Class

I have the following code, although I am trying to output:
fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);
Although I get the following error:
The name 'e' does not exist in the current context
My code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWatcherr
{
class Program
{
static void Main(string[] args)
{
string dirPath = "C:\\";
FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath);
fileWatcher.IncludeSubdirectories = true;
fileWatcher.Filter = "*.exe";
// fileWatcher.Filter = "C:\\$Recycle.Bin";
// fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
// fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
// fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
fileWatcher.EnableRaisingEvents = true;
// updated code
using(StreamWriter fileWriter = new StreamWriter("test2.txt"))
{
var data = true;
fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);
}
Console.ReadKey();
}
static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine(e.OldName + " was renamed to " + e.Name);
}
static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " was deleted");
}
static void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("C:\\" + e.Name);
}
static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "");
}
}
}
The e refers to the EventArgs parameter of the event methods.
If you put this:
using(StreamWriter fileWriter = new StreamWriter("test2.txt"))
{
var data = true;
fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);
}
in the
static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
method, it should work.
From what I can see in the code, you have the code for the Rename event inside the main method which does not contain a FileSystemEventArgs object (called "e.")
I think to resolve this problem you should change the body of "FileWatcher_Renamed" to the using block.

Categories

Resources