csv export changes comma position in floating point strings - c#

when i export string values which contains decimal numbers like 6,7014
while exporting to csv file it is converting into strange value 67,014
which is inappropriate
function i used is given below:
public void DownloadtoCSV(DataSet ds, String name)
{
string deLimiter = ";";
if (System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol == "$")
{
deLimiter = ",";
}
StringBuilder sb = new StringBuilder();
sb.Append("sep=" + deLimiter + "\r\n");
foreach (DataTable dataTable in ds.Tables)
{
if (dataTable.Columns.Count != 0)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (i == 0)
{
sb.Append(dataTable.Rows[0][i].ToString().Replace(",", " ").Replace("\r\n", " "));
}
else
{
sb.Append(deLimiter + dataTable.Rows[0][i].ToString().Replace(",", " ").Replace("\r\n", " "));
}
}
sb.Append("\r\n");
Int64 k = 0;
if (dataTable.Rows.Count > 0)
{
foreach (DataRow row in dataTable.Rows)
{
if (k != 0)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (i == 0)
{
sb.Append("\"" + row[dataTable.Columns[i].ColumnName].ToString().Replace("\"", "\"\"").Replace("\r\n", " ") + "\"");
}
else
{
sb.Append(deLimiter + "\"" + row[dataTable.Columns[i].ColumnName].ToString().Replace("\"", "\"\"").Replace("\r\n", " ") + "\"");
}
}
sb.Append("\r\n");
}
k++;
}
}
}
sb.Append(Environment.NewLine);
}
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Response.ContentType = "Application/save";
Response.AddHeader("content-disposition", "attachment;filename=" + name + ".csv");
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
}`enter code here`

Related

Extract elements from List string built using c #

I have this string
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
that is composed of this c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('value1:\\n" +
string.Join(",", value1) + "');", true);
Using the code above the output is
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
Now I need to extract from this string from element number 5 to all subsequent elements, that is
2022-006,related,2022-007,related
and storing a row for each string value in a database table, that is
t
q
2022-006
related
2022-017
related
Expected output
2022-006
related
2022-017
related
But the expected ouput now is empty...
This is my c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
List<string> value2 = item.Split(',').ToList();
for (int i = 4; i < value2.Count; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
}
}
Thanks in advance for any help, really appreciated.
Solution
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
var requestDLL = string.Join(",", value1);
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
Output
2022-006
related
2022-017
related
Here you can find the code that return the expected output https://dotnetfiddle.net/8aBrZj
using System;
public class Program
{
public static void Main()
{
var requestDLL = "Dispatching System,proposal,to be sent,main,2022-006,related,2022-017,related";
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Console.Write(value2[i] + "\n" + value2[i + 1] + "\n \n");
i++;
}
}
}

The process cannot access the file "XXX.txt" because it is being used by another process

I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.

How to fix 'The name 'k' does not exist in the current context' error?

I only get the System.IndexOutOfRangeException error when running the solution normally but is all okay when stepping into through the whole loop.
I have tried the to catch the exception but no joy.
private void button1_Click(object sender, EventArgs e)
{
for (int j = 0; j < jobs.Length; j++)
{
if (jobs[j].JobID == false)
{
for (int k = 0; k < threads.Length; k++)
{
if (threads[k] != null)
{
if (!(threads[k].ThreadState == ThreadState.Stopped) | !(threads[k].ThreadState == ThreadState.Unstarted))
{
continue;
}
}
try
{
threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[j].FTPFolder, HomePath + jobs[j].localFolder, j));
threads[k].Name = "Thread " + j + "¦ ID: " + threads[k].ManagedThreadId.ToString();
jobs[j].JobID = true;
//threads[k].Start();
break;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
}
StartThreads();
}
I expect all threads in the threads[] array to be initialised if jobs[].JobID is false.
Below is the CountUp() method:
private void CountUp(string ftppath,string localFile, int jobsID)
{
//string conf="";
NumberThreads++;
//string ftpPath = "ftp://ftp.Rxsystems.net" + conf.Split('¦')[1];
//string downloadPath = HomePath + conf.Split('¦')[0] + "\\";
string ftpPath = ftppath;
string downloadPath = localFile;
List<string> MSI = new List<string>(KD.FTP.Class.ListFiles(ftpPath,
FTPuser, FTPpass));
if (MSI.Count > 0)
{
KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath, CurDir + "\\log.txt");
this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath);
//this.textBox1.AppendText("\n\r");
int count = 0;
foreach (string ftpFile in MSI)
{
KD.FTP.Class.Download(ftpPath + ftpFile,downloadPath + "\\" + ftpFile, FTPuser,FTPpass);
count++;
KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile, CurDir + "\\log.txt");
this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile);
//this.textBox1.AppendText("\n\r");
}
}
NumberThreads--;
jobs[jobsID].JobID = false;
}
The below initialises threads[] and jobs[]:
private void Form1_Load(object sender, EventArgs e)
{
Form1.CheckForIllegalCrossThreadCalls = false;
if (File.Exists(CurDir + "\\FTPpaths.config"))
{
foreach (string line in File.ReadAllLines(CurDir + "\\FTPpaths.config"))
{
if (!string.IsNullOrEmpty(line))
{
ConfigPaths.Add(line.Split('¦')[0] + "¦" + line.Split('¦')[1]);
}
}
if (ConfigPaths.Count > 0)
{
jobs = new Jobs[ConfigPaths.Count];
for (int j = 0; j < ConfigPaths.Count; j++)
{
jobs[j] = new Jobs();
jobs[j].FTPFolder = ConfigPaths[j].Split('¦')[1];
jobs[j].localFolder = ConfigPaths[j].Split('¦')[0];
jobs[j].JobID = false;
}
threads = new Thread[jobs.Length];
}
timer1.Enabled = true;
}
else
{
Application.Exit();
}
}
From what I can see the problem is with j variable which is captured from closure into delegate passed to new Thread. It's well know problem when actual delegate execution references the variable in state after the loop execution so it's supposed to effectively contain jobs.Length value which is out of range. To fix you need to introduce a local variable inside the loop to copy j value in, and then use this variable instead of j as index of jobs inside the delegate passed to the Thread constructor:
try
{
var jobIdx = j;
threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[jobIdx].FTPFolder, HomePath + jobs[jobIdx].localFolder, jobIdx));
...
// other stuff
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}

C# serial port close hang while close the application

this is my code
public void ClosePort()
{
if (comPort.IsOpen == true)
{
//e.Cancel = true; //cancel the fom closing
Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang
//comPort.DiscardInBuffer();
//comPort.DiscardOutBuffer();
//comPort.Dispose();
CloseDown.Start(); //close port in new thread to avoid hang
DisplayData(MessageType.Error, "Port communication has been closed" + " " + DateTime.Now + "\n");
}
}
private void CloseSerialOnExit()
{
try
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //close the serial port
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //catch any serial port closing error messages
}
BeginInvoke(new EventHandler(NowClose)); //now close back in the main thread
}
private void NowClose(object sender, EventArgs e)
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //now close the form
}
public void BeginInvoke(Delegate method)
{
}
why the serial port not close? and when i hit [X] Icon and exit the program, program stil detect in task manager.
In normal case, the above code is work. But when the serial do write or read data the code is not work, not close the serial port, any suggestion for this case? thanks for help and solution.
private void cmdClose_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure to disconnect?", "WARNING",
MessageBoxButtons.OKCancel);
switch (result)
{
case DialogResult.OK:
{
comm.ClosePort();
cmdRefresh.Enabled = true;
cmdNewReport.Enabled = true;
cboPort.Enabled = true;
cboBaud.Enabled = true;
cboStop.Enabled = true;
cboParity.Enabled = true;
cboData.Enabled = true;
label9.Text = " ";
label11.Text = " ";
cmdOpen.Enabled = true;
//cmdSend.Enabled = true;
cmdClose.Enabled = false;
break;
}
case DialogResult.Cancel:
{
break;
}
}
}
the above code is my button code which calling the comPort.ClosePort();
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//determine the mode the user selected (binary/string)
switch (CurrentTransmissionType)
{
//user chose string
case TransmissionType.Text:
//read data waiting in the buffer
string msg = comPort.ReadExisting();
//display the data to the user
DisplayData(MessageType.Incoming, msg + "\n");
break;
//user chose binary
case TransmissionType.Hex:
//retrieve number of bytes in the buffer
int OpeCode = 0;
int RequestID = 0;
int Product = 0;
int IPenNo = 0;
string status = " ";
while (true)
{
DateTime time = DateTime.Now; // Use current time.
string format = "dddddddd, MMMMM d, yyyy HH:mm:ss";
string currentTime = time.ToString(format);
byte[] TrueData = new byte[256];
try
{
int bytes = comPort.BytesToRead;
if (bytes == 0) continue;
//create a byte array to hold the awaiting data
byte[] comBuffer = new byte[bytes];
comPort.Read(comBuffer, 0, bytes);
DisplayData(MessageType.Incoming, "Hexa :" + ByteToHex(comBuffer) + "\n");
DisplayData(MessageType.Incoming, "Byte :" + bytes.ToString() + "\n");
if (bytes == 3)
{
var lines = File.ReadAllLines(Fullpath).ToList();
// Remove as many lines as you'd like from the end
if (lines.Count > 2)
{
lines.RemoveRange(lines.Count - 2, 2);
}
// Iterate backwards through the list until we've updated 2 (or more or less) lines
var linesUpdated = 0;
for (var i = lines.Count - 1; i >= 0 && linesUpdated < 1; i--)
{
if (lines[i].Contains("OK"))
{
lines[i] = lines[i].Replace("OK", "NG");
linesUpdated++;
}
}
File.WriteAllLines(Fullpath, lines.ToArray());
//DisplayData(MessageType.Incoming, "NG" + "\n");
}
if (bytes == 2)
{
continue;
}
int etx_ok = 0;
for (int i = 0; i < bytes; i++)
{
if (comBuffer[i] == 0x02)
{
//DisplayData(MessageType.Incoming, "cek II:" + checkStatus + "\n");
int length = comBuffer[i + 1];
DisplayData(MessageType.Incoming, "Length=" + length.ToString() + "\n");
if (String.IsNullOrEmpty(bytes.ToString()))
{
status = "NG";
}
if (length + i + 1 != bytes && status == " ")
{
DisplayData(MessageType.Incoming, length.ToString() + " " + i.ToString() + " " + bytes.ToString() + " ");
status = "NG";
DisplayData(MessageType.Incoming, "ERROR \n");
//break;
}
else
{
status = "OK";
}
DisplayData(MessageType.Incoming, "ini statusnya : " + status + "\n");
if (comBuffer[length + i - 1] == 0x03)
{
DisplayData(MessageType.Incoming, "ETX OK\n");
etx_ok = 1;
OpeCode = comBuffer[i + 2];
DisplayData(MessageType.Incoming, "OpeCode=" + OpeCode.ToString() + ",");
RequestID = comBuffer[i + 3];
DisplayData(MessageType.Incoming, "RequestID=" + RequestID.ToString() + ",");
int StoreCode = comBuffer[i + 4];
DisplayData(MessageType.Incoming, "StoreCode=" + StoreCode.ToString() + ",");
int ProductBatteryTraining = comBuffer[i + 5];
DisplayData(MessageType.Incoming, "ProductBatteryTraining=" + ProductBatteryTraining.ToString() + ",");
Product = ProductBatteryTraining >> 4;
DisplayData(MessageType.Incoming, " Product=" + Product.ToString() + ",");
int Battery = ProductBatteryTraining & 4;
DisplayData(MessageType.Incoming, " Batery=" + Battery.ToString() + ",");
int Training = ProductBatteryTraining & 1;
DisplayData(MessageType.Incoming, " Training=" + Training.ToString() + ",");
IPenNo = comBuffer[i + 6];
DisplayData(MessageType.Incoming, "IPenNo=" + IPenNo.ToString() + ",");
int CrcCalc = comBuffer[length + i] + 0x11;
for (int j = 7, k = 0; j < length; j++, k++)
{
//syswrite STDOUT , "TrueDataX " . $length . "\n";
DisplayData(MessageType.Incoming, "TrueDataX " + length.ToString() + "," + "\n");
TrueData[k] = comBuffer[i + j];
}
if (OpeCode == 0x63)
{
byte[] replyStr = new byte[] {
Convert.ToByte(0x45), Convert.ToByte(0x53), Convert.ToByte(0x4c), Convert.ToByte(0x14), Convert.ToByte(0x09), Convert.ToByte(0x00), //#Length Change
Convert.ToByte(0x02), Convert.ToByte(0x08),Convert.ToByte(OpeCode), Convert.ToByte(RequestID),Convert.ToByte(Product-1), Convert.ToByte(IPenNo), //#Reply Header Data
Convert.ToByte(0x00), //#Reply Status
Convert.ToByte(0x03), Convert.ToByte(CrcCalc), //#Footer Data
Convert.ToByte(0xcc), Convert.ToByte(0xcc)
};
comPort.Write(replyStr, 0, replyStr.Length);
//write file to textfile
//string path = #"d:\yosafat\testfile\tes1_Friday0916201614.33.txt";
string IPenID = IPenNo.ToString();
string appendText = ("IPen ID \t" + "Datetime\t\t\t\t\t" + "Status" + Environment.NewLine + IPenID + "\t\t" + currentTime + "\t\t" + status + Environment.NewLine);
File.AppendAllText(Fullpath, appendText);
}
}
else
{
OpeCode = 0;
//syswrite STDOUT , "ETX Bad Data" . $length . "\n";
DisplayData(MessageType.Incoming, "ETX Bad Data" + length.ToString() + "\n");
break;
}
}
if (etx_ok == 1)
{
break;
}
}
}
catch (Exception) { }
}
}
}

Alternative to ReadLine?

I'm trying to read some files with ReadLine, but my file have some break lines that I need to catch (not all of them), and I don't know how to get them in the same array, neither in any other array with these separators... because... ReadLine reads lines, and break these lines, huh?
I can't replace these because I need to check it after the process, so I need to get the breaklines AND the content after that. That's the problem. How can I do that?
Here's my code:
public class ReadFile
{
string extension;
string filename;
System.IO.StreamReader sr;
public ReadFile(string arquivo, System.IO.StreamReader sr)
{
string ext = Path.GetExtension(arquivo);
sr = new StreamReader(arquivo, System.Text.Encoding.Default);
this.sr = sr;
this.extension = ext;
this.filename = Path.GetFileNameWithoutExtension(arquivo);
if (ext.Equals(".EXP", StringComparison.OrdinalIgnoreCase))
{
ReadEXP(arquivo);
}
else MessageBox.Show("Extensão de arquivo não suportada: "+ext);
}
public void ReadEXP(string arquivo)
{
string line = sr.ReadLine();
string[] words;
string[] Separators = new string[] { "<Segment>", "</Segment>", "<Source>", "</Source>", "<Target>", "</Target>" };
string ID = null;
string Source = null;
string Target = null;
DataBase db = new DataBase();
//db.CreateTable_EXP(filename);
db.CreateTable_EXP();
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("<Segment>"))
{
ID = "";
words = line.Split(Separators, StringSplitOptions.None);
ID = words[0];
for (int i = 1; i < words.Length; i++ )
ID += words[i];
MessageBox.Show("Segment[" + words.Length + "]: " + ID);
}
if (line.Contains("<Source>"))
{
Source = "";
words = line.Split(Separators, StringSplitOptions.None);
Source = words[0];
for (int i = 1; i < words.Length; i++)
Source += words[i];
MessageBox.Show("Source[" + words.Length + "]: " + Source);
}
if (line.Contains("<Target>"))
{
Target = "";
words = line.Split(Separators, StringSplitOptions.None);
Target = words[0];
for (int i = 1; i < words.Length; i++)
Target += words[i];
MessageBox.Show("Target[" + words.Length + "]: " + Target);
db.PopulateTable_EXP(ID, Source, Target);
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
catch (IndexOutOfRangeException e)
{
MessageBox.Show(e.Message.ToString());
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
return;
}
If you are trying to read XML, try using the built in libaries, here is a simple example of loading a section of XML with <TopLevelTag> in it.
var xmlData = XDocument.Load(#"C:\folder\file.xml").Element("TopLevelTag");
if (xmlData == null) throw new Exception("Failed To Load XML");
Here is a tidy way to get content without it throwing an exception if missing from the XML.
var xmlBit = (string)xmlData.Element("SomeSubTag") ?? "";
If you really have to roll your own, then look at examples for CSV parsers,
where ReadBlock can be used to get the raw data including line breaks.
private char[] chunkBuffer = new char[4096];
var fileStream = new System.IO.StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
var chunkLength = fileStream.ReadBlock(chunkBuffer, 0, chunkBuffer.Length);

Categories

Resources