Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Login
Sign Up
Ask Question
1
Reply
c# and serial-port communication
Ungureanu Victor
Dec 5 2017 2:14 AM
173
Reply
I'm trying to do an application in c #, which sends a text file through a serial port to a machine. all good and beautiful if the machine is put in download mode. if the operator forgets to put the machine on download mode .... here comes the problem, I have a writetimout exception. I would like to use this exception or anything else to resume the process and my program will try to reload the file into the machine. below is my code
private
void
incarca_button_Click(object sender, EventArgs e)
{
string open_folder = cale_txt.Text.Replace(Environment.NewLine,
""
);
OpenFileDialog theDialog =
new
OpenFileDialog();
theDialog.Title =
"Open Text File"
;
theDialog.Filter =
"TXT files|*.txt"
;
theDialog.InitialDirectory = open_folder;
if
(theDialog.ShowDialog() == DialogResult.OK)
{
var onlyFileName = System.IO.Path.GetFileName(theDialog.FileName);
piesa_lbl.Hide();
piesa_txt.Hide();
SerialPort cnc_com =
new
SerialPort(com);
cnc_com.BaudRate = Int32.Parse(bit);
parity = parity.ToString();
cnc_com.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
cnc_com.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stop_bit);
cnc_com.DataBits = Int32.Parse(data_bit);
cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
cnc_com.Encoding = Encoding.ASCII;
cnc_com.ReadTimeout = 500;
cnc_com.WriteTimeout = 500;
cnc_com.ReadBufferSize = 1000000;
cnc_com.WriteBufferSize = 1000000;
//cnc_com.DtrEnable = true;
//cnc_com.RtsEnable = true;
try
{
cnc_com.Open();
}
catch
(UnauthorizedAccessException) { }
catch
(System.IO.IOException) { }
catch
(ArgumentException) { }
using
(StreamReader sr =
new
StreamReader(open_folder + @
"\"
+ onlyFileName))
{
while
(sr.Peek() >= 0)
{
try
{
cnc_com.WriteLine(sr.ReadLine());
//cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
}
catch
(TimeoutException wtout)
{
MessageBox.Show(
"Masina nu este pregatita\nReincarcati programul"
);
cnc_com.Close();
cnc_com = null;
}
}
}
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
}
}
I would like this piece of code to be executed only if the file was passed successfully to the machine
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
thank you
Upload Source Code
Select only zip and rar file.
Post
Reset
Cancel
Answers (
1
)
Next Recommended Forum
Need Help With Part of a Program
c# cha database and tally cha database kasa connect kartat