C# Help - FileSystemWatcher Class - c#

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.

Related

Can't Close SerialPort, arduino sending with 200hz data to serial monitor

Halllo
I have made my first project and it works, well sort of, I can not get it to close serial port.
I am running 200hz in the Serialmonitor and the save funktion works perfect.
I suspect that it attempts to read data while I am trying to close the port.
It does not come up with an error but hanging in the debugger trying to close the port.
MY CODE IN VISUAL STUDIO 2015:
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace Arduino_Serial
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data1;
private int runtime_sec = 0;
private float runtime_milis = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click_1(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = Port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += Myport_DataReceived;
try
{
myport.Open();
timer2.Enabled = true;
timer1.Enabled = true;
Data_tb.Text = "\"Arduino\"" + "\n";
Data_tb.AppendText("Time" + "\t" + "Raw_data" + "\t" + "MAP" + "\n");
Data_tb.AppendText("Sec " + "\t" + "Raw_data" + "\t" + "KPA" + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
void Myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data1 = myport.ReadLine();
Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
Data_tb.AppendText(("\n")+ (runtime_milis) + ("\t")+ in_data1 );
}
private void Stop_bt_Click(object sender, EventArgs e)
{
try
{
myport.ReadTimeout = 1000000000;
myport.Close();
timer2.Enabled = false;
timer1.Enabled = false;
runtime_milis = 0;
runtime_sec = 0;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void Save_bt_Click(object sender, EventArgs e)
{
try
{
datetime = DateTime.Now;
String time = datetime.Year + "-"+ datetime.Month + "-"+ datetime.Day + "_" + datetime.Hour + "." + datetime.Minute + "." + datetime.Second;
string pathfile = #"C:\DATA\";
string filename = "Arduino_" + time + ".msl";
System.IO.File.WriteAllText(pathfile + filename, Data_tb.Text);
MessageBox.Show("Data has been saved");
Close();
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
runtime_sec++;
}
private void timer2_Tick(object sender, EventArgs e)
{
runtime_milis++;
}
}
}

Expected behaviour with white space in the command line

I wrote a program that compiles my .cs files using csc.exe:
namespace myCompiler
{
public partial class Form1 : Form
{
string compilerFolder;
string outputFolder;
string projectFile;
string output = #" /out:";
public Form1()
{
InitializeComponent();
}
private void startCompile_Click(object sender, EventArgs e)
{
Compile();
}
public void findCompile_Click(object sender, EventArgs e)
{
DialogResult result1 = folderBrowserDialog1.ShowDialog();
compilerFolder = folderBrowserDialog1.SelectedPath;
MessageBox.Show(compilerFolder);
cscLabel.Text = compilerFolder;
}
private void outputCompile_Click(object sender, EventArgs e)
{
DialogResult result2 = folderBrowserDialog2.ShowDialog();
outputFolder = folderBrowserDialog2.SelectedPath;
outputLabel.Text = (outputFolder);
MessageBox.Show(outputFolder);
}
private void findProject_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
projectFile = openFileDialog1.FileName;
projectLabel.Text = (projectFile);
MessageBox.Show(projectFile);
}
}
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + #"\csc.exe";
string arGs = output + outputFolder + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = (compiler);
compile.StartInfo.Arguments = (arGs);
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
private void testButton_Click(object sender, EventArgs e)
{
MessageBox.Show(projectFile);
MessageBox.Show(compilerFolder);
}
}
}
The compile instruction runs but produces no results, just a quick flash of a black console screen.
Basically what seems to be happening, is when all the strings are parsed in the commandline as arguments for the process, the .cs project source directory is broken up by each white space ie c:\users\%username%\Documents\Visual Studio 2010\ is broken up as c:\users\%username%\Documents\Visual then Studio then 2010\Projects\Myproject\myproj.cs
and subsequently the compilation fails.
You need double quotes around a filepath with spaces in it.
See my edit to your code below.
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + "\csc.exe";
// add double quotes around path with spaces in it.
string arGs = output + "\"" + outputFolder + "\"" + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = compiler;
compile.StartInfo.Arguments = arGs;
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}

windows service exception and stop my service

My Service read from com port and save the info in DB.It works perfectly fine for a while,but sometimes the error window is appeared for getting an exception,and if I don't click 'no' buttun , it doesn't read from com port.When I check in event viewer,I see some exception number 7034,7031 on my service.I log every where in my code and I use try,catch .I don't have ant catch in my log file,so I can't understand what is the problem?
public partial class Service1 : ServiceBase
{
string _fileName = #"c:\logSensor\log.ini";
internal delegate void StringDelegate(string data);
ArrayList lines = new ArrayList();
BL.EnterDatas eData = new BL.EnterDatas();
private class Line
{
public string Str;
public Line(string str)
{
Str = str;
}
}
public Service1()
{
InitializeComponent();
CommPort com = CommPort.Instance;
com.Open();
com.StatusChanged += OnStatusChanged;
com.DataReceived += OnDataReceived;
timer1.Enabled = true;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() +
" . " + "Step1:Load ");
writer.Flush();
}
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "timer1_Elapsed:Stop Timer ");
writer.Flush();
}
ReadLog();
StreamReader sr = new StreamReader(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\path.txt");
string _logPath = sr.ReadLine();
FileStream fs = new FileStream(_logPath, FileMode.Open);
fs.SetLength(0);
fs.Close();
}
catch (Exception ex)
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "Catch:timer1_Elapsed " + ex.Message);
writer.Flush();
}
}
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "final:timer1_Elapsed ");
writer.Flush();
}
timer1.Start();
}
#region Functions...
...
}

How to access additional classes in events

I'm trying to access the Script class that is in the code block below in the event triggered when a file download is completed. How would I be able to do that?
public void DownloadScript(Script script, string DownloadLocation)
{
AddLog(GenerateLog("Downloading Script", "Started", "Downloading " + script.Name + " from " + script.DownloadURL + "."));
WebClient Client = new WebClient();
Client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Client_DownloadFileCompleted);
Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
Client.DownloadFileAsync(new Uri(script.DownloadURL), DownloadLocation + "test1.zip");
}
Here is the event that is triggered.
public void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error.Message != string.Empty)
{
AddLog(GenerateLog("Downloading Script", "Error", "There was an error downloading " + script.Name + " from " + script.DownloadURL + ". " + e.Error.Message));
Console.WriteLine("Error");
}
else
{
AddLog(GenerateLog("Downloading Script", "Done", "Finished downloading " + script.Name + " from " + script.DownloadURL + "."));
Console.WriteLine("Done");
}
}
You can use a lambda expression to capture the Script object and pass it along to the handler as an extra parameter.
public void DownloadScript(Script script, string DownloadLocation) {
...
WebClient Client = new WebClient();
Client.DownloadFileCompleted += (sender, e) => Client_DownloadFileCompleted(
sender,
e,
script);
}
public void Client_DownloadFileCompleted(
object sender,
AsyncCompletedEventArgs e,
Script script) {
...
}

C# Output text to file on a new line

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.

Categories

Resources