My earlier post was unreadable so.
I am trying to read the last line of a text file every time it changes.
The code I have is,
private void fileSystemWatcherMCH1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
string machState = File.ReadAllLines(#"C:\Users\sgarner\Documents\PROTOMET SHOP FLOOR\Machines\MACHINE_1.txt").Last();
btnMCH1.Text = machState;
btnMCH1.BackColor = Color.Blue;
}
If I only run the btnMCH1.BackColor = Color.Blue; it works. But I cannot read in the variable from the text file.
I am certain I am missing something simple.
Thanks,
It seems that your code is raising an exception but for any reason you're not seeing it. Maybe the file is being used by other process ... Try to catch it and then show it, so, you can see the problem:
private void fileSystemWatcherMCH1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
try
{
string machState = File.ReadAllLines(#"C:\Users\sgarner\Documents\PROTOMET SHOP FLOOR\Machines\MACHINE_1.txt").Last();
btnMCH1.Text = machState;
btnMCH1.BackColor = Color.Blue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Messasge);
}
}
Related
I am making a GUI to a bigger program.
In order to include a Abort button, i had to use Backgroundworker.
void _oWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Starter.Handling(cBLog, cBSelC, cBSelT);
if (_oWorker.CancellationPending)
{
e.Cancel = true;
return;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message,"Exception Caught:");
}
}
Now however I have stumbled upon a bigger problem, not beeing able to access the Textbox which is loaded as follows:
private void Form1_Load(object sender, EventArgs e)
{
// Instantiate the writer
_writer = new TextBoxStreamWriter(txtConsole);
// Redirect the out Console stream
Console.SetOut(_writer);
}
The Problem is, the TextBox has to stay the Console Output since I don't want to change the subprograms (which also contain while loops).
Any suggestions?
I trying to load my video from the resources folder but its not playing automatically once my form load. Can I know what mistake i have done. Thank you.
This is my c# code:
private void Form2_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = #"Resources/abc.mp4";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
Well I have solved it my ownself. Actually, I accidentally added the # symbol into my url. That causes the problem. This is the updated code.
private void Form2_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = "Resources\\abc.mp4";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
To do that king of thing, you must get the stream of your resource.
So that code should work for you because works for me :)
// temporary file path - your temp file = video.avi
var strTempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Video.avi");
try
{
// ResourceName = the resource you want to play
File.WriteAllBytes(strTempFile, Properties.Resources.ResourceName);
axWMP.URL = strTempFile;
axWMP.Ctlcontrols.play();
}
catch (Exception ex)
{
// Manage me
}
You can implement a axWMP_PlayStateChange method to remove video.Avi at the end.
Hope it could help you
In my C# application I want to delete file in below scenario.
OpenFileDialog and select any .jpg file.
Display that file in PictureBox.
Delete that file if needed.
I already try while doing step 3 I set default Image to PictureBox just before delete but that is not work.
How can I delete file? Please suggest me.
// Code for select file.
private void btnSelet_Click(object sender, EventArgs e)
{
if (DialogResult.OK == openFileDialog1.ShowDialog())
{
txtFileName.Text = openFileDialog1.FileName;
myPictureBox.Image = Image.FromFile(openFileDialog1.FileName);
}
}
// Code for Delete file
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
//myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + #"\Images\defaultImage.jpg");
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Replacing the image sounds like a good idea - but don't forget to dispose of the old Image that's still holding the file open (and will, by default, until that Image is garbage collected - at some unknown time in the future):
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
var old = myPictureBox.Image;
myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + #"\Images\defaultImage.jpg");
old.Dispose();
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(It may also be possible to Dispose of the Image directly without replacing the image for the PictureBox - it depends on what else you're going to do after deletion - e.g. if the form on which the PictureBox appears is closing that you may want to let that happen first and then just directly dispose of the image).
What my code basically does is it allows the user to browse for a folder that has a bunch of files, and when the user clicks a "Start" button, a code that makes files with the same name and different extensions for the ones in the folder runs. What I want to do is add a cancel button so if the user clicks the start button on a folder that was the incorrect one for example, the user can cancel out, browse to the correct folder, and restart the operation.
This is the code that fires when the start button is clicked:
class ExcelCode
{
public static void DoExcel (string FolderPath)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(FolderPath + ".fdf");
Thread.Sleep(1000);
}
}
What I tried so far after hours upon hours of researching was to have the backgroundworker.CancelAsync(); called on the Cancel button, and a global variable that keeps track of the cancellation, ie. the DoWork() method looks like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if(backgroundWorker1.IsBusy)
for (int i = 0; i < 100; i++)
{
foreach (string file in filePaths)
{
if(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
restartWorker = true;
return;
}
ExcelCode.DoExcel(file);
//write to textbox
}
backgroundWorker1.ReportProgress(i);
}
}
And my RunWorkerComplete method looks like this:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled && restartWorker)
{
if (backgroundWorker1.IsBusy)
{
restartWorker = true;
backgroundWorker1.CancelAsync();
return;
}
MessageBox.Show("Worker has cancelled");
restartWorker = false;
return;
}
}
Start Button:
private void button1_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
restartWorker = true;
backgroundWorker1.CancelAsync();
}
else
{
backgroundWorker1.RunWorkerAsync();
}
button2.Enabled = true;
}
Cancel Button:
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
Now this all works well for cancelling out just once, when I try to start again on a different folder I get this error:
An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code
Additional information: The process cannot access the file 'C:\Users\Pierre\Desktop\Test Folder - Copy\New Text Document - Copy - Copy - Copy - Copy - Copy (8).txt.fdf' because it is being used by another process.
The code has everything I researched on so it should pretty much show my entire progress on this. Any guidance as to what should be done is greatly appreciated.
EDIT: The code actually works for the second folder, that is it generates the file but throws the exception anyway.
You are not explicitly releasing the StreamWriter object, so it will only be released when GC kicks off on the object and releases the file. To avoid this issue, change your DoExcel method as follows:
public static void DoExcel (string FolderPath)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(FolderPath + ".fdf"))
{
Thread.Sleep(1000);
file.Close();
}
}
private void delete_Click(object sender, EventArgs e)
{
convertedText.Text = "";
}
private void copy_Click(object sender, EventArgs e)
{
if (convertedText.Text != "")
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
else... what to put here?
}
The program has two buttons (copy and delete) and one textbox. If I click the 'Copy' button, it copies the text from convertedText.Text without any problem. The 'delete' button also clears the textbox fine.
But if there's nothing in the textbox, the 'copy' button still attempts to copy it which is causing an unexpected behaviour.
So, what code do I add to the 'else' statement...? What I want is that if the textbox has nothing in it, then the clipboard operation won't be used. How to do that?
Thanks in advance!
Don't add an else clause, just have the if by itself, e.g.
private void copy_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(convertedText.Text))
{
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
}
Also, is there any reason why you're copying the text box text to the clipboard and then using the clipboard text to update the text box text? Unless I'm missing something, this should have no effect on the text box, so the code can be simpler:
private void copy_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(convertedText.Text))
Clipboard.SetText(convertedText.Text);
}
Your error stems from the fact that you are missing some parentheses there:
if (convertedText.Text != "")
{
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
Only the first line after an if statement is considered to be part of what gets executed dependent on the evaluation of the if when you are omitting parentheses.
You could also return if the textbox does not have a value...
private void copy_Click(object sender, EventArgs e)
{
if (convertedText.Text.Equals(""))
return;
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
maybe you are missing brackets { and }
if (convertedText.Text != ""){
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
else
Try putting
try
{
string foo = "bar" + 42;
}
catch
{
throw;
}