void BuildProjects()
{
String outputPath = #"D:\PIT\ProcessImprovementTool\DLL";
console = new Process();
console.StartInfo.FileName = "cmd.exe";
console.StartInfo.UseShellExecute = false;
console.StartInfo.CreateNoWindow = true;
console.StartInfo.RedirectStandardInput = true;
console.StartInfo.RedirectStandardOutput = true;
console.StartInfo.RedirectStandardError = true;
console.Exited += new EventHandler((sender, e) =>
{
Console.WriteLine("if (console.Exited) --> ExitCode: " + console.ExitCode);
BuildProjects();
});
console.OutputDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
console.ErrorDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
console.Start();
using (StreamWriter sw = console.StandardInput)
{
sw.AutoFlush = true;
console.StandardInput.AutoFlush = true;
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("D:\\PIT\\ProcessImprovementTool\\callVcvars32.bat");
sw.WriteLine("cls");
for (int ctr = 0; ctr < 5; ctr++)
{
sw.WriteLine("msbuild /property:OutputPath=" + outputPath + #";OutputType=Library " + lines[ctr]);
//console.BeginOutputReadLine();
sw.Flush();
}
}
if (tryout)
{
Console.WriteLine("working");
}
sw.Close();
//sw.Flush();
}
console.BeginOutputReadLine();
console.BeginErrorReadLine();
//console.WaitForExit();
counter++;
}
in the
for (int ctr = 0; ctr < 5; ctr++)
{
sw.WriteLine("msbuild /property:OutputPath=" + outputPath + #";OutputType=Library " + lines[ctr]);
//console.BeginOutputReadLine();
sw.Flush();
}
if i set the limit for ctr to 40 (ctr < 40) my application hangs, and I get that the stream is already at its limit.
Based on my research, .Flush() should do the trick. or setting AutoFlush to True, but doesn't seem to work.
so how do I clear previous stream records, or anything that would let me input more than 40 lines? (i got 100+ but not more than 150 lines to write in streamWriter).
lines variable stores the value of "build.txt".
void readFromBuild()
{
doneReading = true;
lines = System.IO.File.ReadAllLines(#"D:\PIT\ProcessImprovementTool\Build\build.txt");
//System.Console.WriteLine("Contents of WriteLines2.txt = ");
foreach (string line in lines)
{
lineCount++;
}
Console.WriteLine(lineCount);
lineCount = lineCount - limit;
}
"build.txt" contains all files to be compiled to produce DLL files.
For me, this is as good as answered. I just did it in another way, though it may not be that good.
buildProgress.Enabled = true;
buildProgress.Maximum = lineCount;
for (int ctr = 0; ctr < lineCount; ctr++)
{
String outputPath = #"Q:\";
StreamReader reader;
String outputLine;
console = new Process();
console.StartInfo.FileName = "cmd.exe";
console.StartInfo.UseShellExecute = false;
console.StartInfo.CreateNoWindow = true;
console.StartInfo.RedirectStandardInput = true;
console.StartInfo.RedirectStandardOutput = true;
console.StartInfo.RedirectStandardError = true;
console.Start();
using (StreamWriter sw = console.StandardInput)
{
sw.AutoFlush = true;
console.StandardInput.AutoFlush = true;
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(#"Q:\");
sw.WriteLine("msbuild /property:OutputPath=" + outputPath + #";OutputType=Library " + lines[ctr]);
sw.Flush();
}
sw.Close();
}
reader = console.StandardOutput;
outputLine = reader.ReadToEnd();
console.WaitForExit();
//if (console.HasExited)
//{
Console.Write(outputLine);
//outputTextBox.Text += outputLine;
pathToLog = #"Q:\" + fileList[ctr];
File.Create(pathToLog).Dispose();
File.WriteAllText(pathToLog, outputLine);
buildProgress.Value = ctr;
string[] readThatLog = File.ReadAllLines(pathToLog);
foreach(string line in readThatLog)
{
if (line == "Build succeeded.")
{
outputTextBox.AppendText(lines[ctr]);
outputTextBox.AppendText(Environment.NewLine + line);
outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
}
else if (line == "Build FAILED.")
{
outputTextBox.AppendText(lines[ctr]);
outputTextBox.AppendText(Environment.NewLine + line);
outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
}
}
//}
}
buildProgress.Value = 0;
buildProgress.Enabled = false;
Console.WriteLine("\n\n\n\nDONE!!!");
Related
I have a WPF App that allows the user to choose one to many spreadsheets and performs a process to clean the data and write out a pipe delimited files. I am trying to use a Background Worker in order to display a progress bar. The problem I am having is that I have the backgroundworker_DoWork routine to perform the read the excel file, clean the data and write out the data. For each spreadsheet the user is allowed to specify the range for the data or to let Excel decided the range. I call a dialog for this input. I get the error "The calling thread must be STA, because many UI components require this." I have been trying to find a fix for this but everything I try doesn't work.
Here is my code. I have put comments where the offending code is and what I have tried so far.
private void ProcessFiles()
{
int intNumFiles = 0;
string strFileType = "";
int intPos = 0;
string strMsg = "";
intNumFiles = strExFileNames.Length;
foreach (string strInputFile in strExFileNames)
{
intPos = strInputFile.LastIndexOf(".");
strFileType = strInputFile.Substring(intPos + 1);
if(!blnEXTextFileFound)
{
strExcelInputFile = strInputFile;
if (blnExParamCancel || blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
break;
}
prgExcelProgress.Visibility = Visibility.Visible;
txtExcelPercent.Visibility = Visibility.Visible;
EnterExcelStateRunning();
try
{
bgwExcelRunner.RunWorkerAsync(strInputFile);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Trying to run the Excel/Text file clean process resulted in this error: " + ex.Message, " Error");
prgExcelProgress.Foreground = new SolidColorBrush(Colors.DarkRed);
prgExcelProgress.Value = 100;
}
//ReadWriteExcelData(strInputFile);
}
else
{
if (blnEXTextFileFound)
{
ProcessDelimitedFile(strInputFile);
}
else
{
strMsg = "File type " + strFileType + " is not supported.";
strMsg += " Please contact support.";
System.Windows.MessageBox.Show(strMsg);
}
}
}
prgExcelProgress.Value = 100;
//prgIndicator.Width = 400;
//lblPrctPrgrs.Content = "100%";
//grdProgressIndicator.InvalidateVisual();
//System.Windows.Forms.Application.DoEvents();
//Thread.Sleep(2000);
//txtIndicator.Text = "All files have been processed and created in " + strExOutputPath + ".";
blnDoForAll = false;
}
private void bgwExcelRunner_DoWork(object sender, DoWorkEventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range, colrange, rowrange;
string strCellData, strMsg;
string strDataRow = "";
long lngNumRows, lngNumCols = 0;
long intModNumber, lngProgressPct = 0;
double dblProgress = 0;
double dblProgressPct = 0;
string strOutputFileName = "";
int intPos, intProgress = 0;
string strSubFileName = "";
string strFullOutputFileName = "";
string strOutName = "";
long lngColCnt;
string[] strWSNames = new string[0];
Type typCellType;
bool blnMultiWS = false;
string strNumberFormat;
string strFileName = (string)e.Argument;
//string strFileName = (string)((object[])e.Argument)[0];
intPos = strFileName.IndexOf(".");
strSubFileName = strFileName.Substring(0, intPos);
strOutputFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
strOutName = strOutputFileName.Substring(0, strOutputFileName.IndexOf("."));
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(strFileName, 0, true, 5, "", "", true,
Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Sheets excelSheets = xlWorkBook.Worksheets;
if (excelSheets.Count > 1)
{
blnMultiWS = CheckMultipleWorksheets(excelSheets);
if (!blnMultiWS)
{
Array.Clear(strChoosenNames, 0, strChoosenNames.Length);
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
}
else
{
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
if (blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
goto ReadWriteExcelDataExit;
}
foreach (string strCurrWSName in strChoosenNames)
{
//grdProgressIndicator.Visibility = Visibility.Visible;
//txtIndicator.Text = "File: " + strCurrWSName;
//prgIndicator.Width = 0;
//lblPrctPrgrs.Content = "0%";
//System.Windows.Forms.Application.DoEvents();
//txtIndicator.Text = " Processing File: " + strCurrWSName + ". Please wait...";
strFullOutputFileName = strExOutputPath + "\\" + strCurrWSName + "_duc.txt";
//if (strChoosenNames.Length > 1)
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
//}
//else
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//}
try
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
}
catch (Exception exQuery)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
if (!blnDoForAll)
{
// I ALSO TRIED TO USE A THREAD. THIS SEEMS TO WORK EXCEPT THAT IT PROCESSING DOESN'T RUN IN THE FOREGROUND SO IT FALLS TO THE CODE AFTER BEFORE THE DIALOG IS DISPLAYED
//Thread thread = new Thread(() =>
//{
// ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
// ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
// ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// strExcelStartCol = ercWin.strStartCol;
// strExcelEndCol = ercWin.strEndCol;
// lngExcelStartRow = ercWin.lngStartRow;
// lngExcelEndRow = ercWin.lngEndRow;
// blnLetExcelDecide = ercWin.blnExcelDecide;
// blnDoForAll = ercWin.blnDoForAll;
//});
//thread.SetApartmentState(ApartmentState.STA);
//thread.IsBackground = false;
//thread.Start();
// THIS IS ONE ATTEMPT TO USE A DISPATCHER, STILL GET THE STA ERROR
//ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
//ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
//ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
//ercWin.Dispatcher.BeginInvoke
// (
// System.Windows.Threading.DispatcherPriority.Normal,
// (Action)(() =>
// {
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// }
// )
// );
// THIS IS WHERE THE ERROR OCCURS
ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
ercWin.ShowDialog();
blnExParamCancel = ercWin.blnExCancel;
if (blnExParamCancel)
{
prgExcelProgress.Foreground = new SolidColorBrush(Colors.LightPink);
Dispatcher.BeginInvoke((Action)delegate
{
prgExcelProgress.Value = 100;
txtExcelPercent.Text = "Process has been cancelled";
});
blnExParamCancel = false;
goto ReadWriteExcelDataExit;
}
strExcelStartCol = ercWin.strStartCol;
strExcelEndCol = ercWin.strEndCol;
lngExcelStartRow = ercWin.lngStartRow;
lngExcelEndRow = ercWin.lngEndRow;
blnLetExcelDecide = ercWin.blnExcelDecide;
blnDoForAll = ercWin.blnDoForAll;
if (blnLetExcelDecide)
{
range = xlWorkSheet.UsedRange;
}
else
{
Excel.Range c1 = xlWorkSheet.Cells[lngExcelStartRow, strExcelStartCol];
Excel.Range c2 = xlWorkSheet.Cells[lngExcelEndRow, strExcelEndCol];
range = (Excel.Range)xlWorkSheet.get_Range(c1, c2);
}
colrange = range.Columns;
lngNumCols = colrange.Count;
rowrange = range.Rows;
lngNumRows = rowrange.Count;
if (lngNumRows < 10)
{
intModNumber = lngNumRows;
}
else
{
intModNumber = lngNumRows / 10;
}
if (System.IO.File.Exists(#strFullOutputFileName))
{
System.IO.File.Delete(#strFullOutputFileName);
}
object[,] values = (object[,])range.Value;
long NumRow = 1;
using (StreamWriter file = new StreamWriter(#strFullOutputFileName, true, Encoding.GetEncoding("iso-8859-1")))
{
while (NumRow <= values.GetLength(0))
{
strDataRow = "";
for (lngColCnt = 1; lngColCnt <= lngNumCols; lngColCnt++)
{
if (values[NumRow, lngColCnt] == null)
{
typCellType = typeof(System.String);
}
else
{
typCellType = values[NumRow, lngColCnt].GetType();
}
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
if (typCellType == typeof(System.DateTime))
{
strCellData = strCellData.Substring(0, strCellData.IndexOf(" "));
}
else
{
if (typCellType == typeof(System.Decimal))
{
if (Convert.ToDecimal(values[NumRow, lngColCnt]) == 0)
{
strCellData = Convert.ToString(0);
}
else
{
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
}
}
else
{
if (typCellType != typeof(System.String))
{
strNumberFormat = range[NumRow, lngColCnt].NumberFormat.ToString();
if (strNumberFormat != "General" && strNumberFormat != "Text" && strNumberFormat != "#")
{
if (typCellType == typeof(System.Double))
{
if (strNumberFormat.IndexOf("[Red]") > 0)
{
strCellData = Convert.ToString(range[NumRow, lngColCnt].Value2);
}
else
{
double dblCellValue = double.Parse(strCellData);
strCellData = dblCellValue.ToString(strNumberFormat);
}
}
}
}
}
}
if (strCellData == null)
{
strCellData = string.Empty;
}
else
{
strCellData = strCellData.Replace("\r\n", " ").Replace("\n", " ").Replace("\r", " ");
}
if (lngColCnt == lngNumCols)
{
strDataRow += strCellData;
}
else
{
strDataRow += strCellData + "|";
}
}
file.WriteLine(strDataRow);
if (NumRow % intModNumber == 0)
{
lngProgressPct = (NumRow / lngNumRows);
bgwExcelRunner.ReportProgress((int)lngProgressPct);
}
NumRow++;
}
}
releaseObject(xlWorkSheet);
}
xlWorkBook.Close(false, null, null);
ReadWriteExcelDataExit:
blnMWCancel = false;
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Here is the entry point for the ExcelRowColInfo window.
public ExcelRowColInfo(string strWSName)
{
InitializeComponent();
strCurrWSName = string.Copy(strWSName);
InitializeExcelParams();
}
I tried to put [STAThread] above this but get the error "Attributre 'STAThread' is not valid on this declaration type. It is only valid on 'Method' declaration.
How do I do this correctly?
I am using threads to upload images on a FTP. Now I have a problem in limiting the number of threads. when I am creating same number of threads equal to images then it's fine i.e. it is working fine. But now I want to create only suppose maximum of 5 number of threads to upload 100 or more images. I have a datatable in which these 100 images are with a unique field ID which stores suppose 0,1,2,3....and so on for every images. Now I want to start only five threads once so that it may start uploading 5 images parallely. On a Timer, I am checking the status of threads and if I found a thread which is not live now, I want to assign it the 6th Image for uploading and in the same way, if I found other thread which finished its uploading/work, I want to give it 7th image to upload and so on. i.e. this process will run until 100 images are uploaded.
Can you please suggest me a structure by using which I may achieve this? Currently I am creating 100 threads for 100 images and it is working perfect. But I am afraid of creating that much number of threads. Will that affect performance?
My Current Code is:
// A page level variable
Thread [] tr=null;
//On Load of the Control
tr = new Thread[dt.Rows.Count];
//tr = new Thread[MaxID];
for (int i = 0; i < dt.Rows.Count; i++)
//for (int i = 0; i < MaxID; i++)
{
tr[i] = new Thread(new ThreadStart(ProcessItems));
tr[i].Name = Convert.ToString(dt.Rows[i]["Id"]);
tr[i].IsBackground = true;
}
//Start each thread
foreach (Thread x in tr)
{
x.Start();
}
//The method which is used to upload images
public object tLock = new object();
private void ProcessItems()
{
//if (dict.Count == 0)
// pthread.Suspend();
//ArrayList toRemove = new ArrayList();
lock (tLock)
{
try
{
//int NoofAttempts = 0;
//foreach (DictionaryEntry e in dict)
//{
//Thread.Sleep(500);
dr = dt.Select("Is_Uploaded=0 And Id=" + Thread.CurrentThread.Name).FirstOrDefault();
uxImageAndProgress pbCtl = panelControl1.Controls[dr["Image_ID"].ToString()] as uxImageAndProgress;
//NoofAttempts = 0;
string Path = "";
if (ftpPath == "")
{
Path = Global.FTPRemotePath + "/ProductImages/" + dr["Image_ID"] + dr["Extension"].ToString();
}
else
{
Path = ftpPath + dr["Image_ID"] + dr["Extension"].ToString();
}
//object[] loader = e.Value as object[];
int length = (int)(dr["ActualData"] as byte[]).Length;
Stream stream = new MemoryStream(dr["ActualData"] as byte[]);
byte[] rBuffer = ReadToEnd(stream);
int d = length - (int)stream.Length;
d = Math.Min(d, rnd.Next(10) + 1);
if (ftpRequest == null)
{
try
{
#region New Code
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(Global.FTPLogIn, Global.FTPPassword);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = true;
ftpRequest.Timeout = 20000;
ftpRequest.ContentLength = length;
byte[] buffer = new byte[length > 4097 ? 4097 : length];
int bytes = 0;
int total_bytes = (int)length;
System.IO.Stream rs = ftpRequest.GetRequestStream();
while (total_bytes > 0)
{
bytes = stream.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
dr["Is_Uploaded"] = 1;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
rs.Close();
#endregion
}
catch (Exception eeex)
{
ftpRequest = null;
if (ErrorText == "")
ErrorText = eeex.Message.ToString();
else
ErrorText = ErrorText + "," + eeex.Message.ToString();
if (Image_IDsToDelete == "")
Image_IDsToDelete = dr["Image_ID"].ToString();
else
Image_IDsToDelete = Image_IDsToDelete + "," + dr["Image_ID"].ToString();
if (NotUploadedFiles == "")
NotUploadedFiles = Convert.ToString(dr["FileName"]);//dr["Image_ID"] + dr["Extension"].ToString();
else
NotUploadedFiles = NotUploadedFiles + ", " + Convert.ToString(dr["FileName"]);
dr["Is_Uploaded"] = true;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
pbCtl.Is_WithError = true;
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), Global.Header, MessageBoxButtons.OK);
//pthread.Suspend();
}
}
}
//The Timer Event on which I am checking the Status of threads and taking appropriate action
private void timer1_Tick(object sender, EventArgs e)
{
bool Is_AllFinished=true;
//Start each thread
foreach (Thread x in tr)
{
if (x.IsAlive == true)
{
Is_AllFinished = false;
break;
}
else
{
//DataRow[] drs = dt.Select("Is_Uploaded=0");
//if (drs.Count() > 0)
//{
//x. = Convert.ToString(MaxID + 1);
//x.Start();
//MaxID = MaxID + 1;
//}
}
}
if (Is_AllFinished == true)
{
timer1.Enabled = false;
if (Image_IDsToDelete != "")
{
RetailHelper.ExecuteNonQuery("Delete from images where Image_ID in (" + Image_IDsToDelete + ")");
}
if (ErrorText != "")
{
NotUploadedFiles = NotUploadedFiles + ".";
XtraMessageBox.Show("Unable to connect to server. The following files were not uploaded:" + System.Environment.NewLine + NotUploadedFiles + ".", Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Is_Done = true;
}
}
Now, I want to convert this code to use a fixed number of threads. Please help me.
Thanking you!
Use a Semaphore it is good enough. You can polish the code yourself.
const int maxThreads = 5;
Semaphore sm = new Semaphore(maxThreads, maxThreads); // maximum concurrent threads
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
sm.WaitOne();
Thread tr = new Thread(new ThreadStart(ProcessItems));
tr.Name = Convert.ToString(dt.Rows[i]["Id"]);
tr.IsBackground = true;
tr.Start();
}
finally
{
sm.Release();
}
}
// You don't need the timer anymore
// Wait for the semaphore to be completely released
for (int i=0; i<maxThreads ; i++)
sm.WaitOne();
sm.Release(maxThreads);
if (Image_IDsToDelete != "")
{
RetailHelper.ExecuteNonQuery("Delete from images where Image_ID in (" + Image_IDsToDelete + ")");
}
if (ErrorText != "")
{
NotUploadedFiles = NotUploadedFiles + ".";
XtraMessageBox.Show("Unable to connect to server. The following files were not uploaded:" + System.Environment.NewLine + NotUploadedFiles + ".", Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//The method which is used to upload images
private void ProcessItems()
{
//if (dict.Count == 0)
// pthread.Suspend();
//ArrayList toRemove = new ArrayList();
try
{
sm.WaitOne();
try
{
//int NoofAttempts = 0;
//foreach (DictionaryEntry e in dict)
//{
//Thread.Sleep(500);
dr = dt.Select("Is_Uploaded=0 And Id=" + Thread.CurrentThread.Name).FirstOrDefault();
uxImageAndProgress pbCtl = panelControl1.Controls[dr["Image_ID"].ToString()] as uxImageAndProgress;
//NoofAttempts = 0;
string Path = "";
if (ftpPath == "")
{
Path = Global.FTPRemotePath + "/ProductImages/" + dr["Image_ID"] + dr["Extension"].ToString();
}
else
{
Path = ftpPath + dr["Image_ID"] + dr["Extension"].ToString();
}
//object[] loader = e.Value as object[];
int length = (int)(dr["ActualData"] as byte[]).Length;
Stream stream = new MemoryStream(dr["ActualData"] as byte[]);
byte[] rBuffer = ReadToEnd(stream);
int d = length - (int)stream.Length;
d = Math.Min(d, rnd.Next(10) + 1);
if (ftpRequest == null)
{
try
{
#region New Code
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(Global.FTPLogIn, Global.FTPPassword);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = true;
ftpRequest.Timeout = 20000;
ftpRequest.ContentLength = length;
byte[] buffer = new byte[length > 4097 ? 4097 : length];
int bytes = 0;
int total_bytes = (int)length;
System.IO.Stream rs = ftpRequest.GetRequestStream();
while (total_bytes > 0)
{
bytes = stream.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
dr["Is_Uploaded"] = 1;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
rs.Close();
#endregion
}
catch (Exception eeex)
{
ftpRequest = null;
if (ErrorText == "")
ErrorText = eeex.Message.ToString();
else
ErrorText = ErrorText + "," + eeex.Message.ToString();
if (Image_IDsToDelete == "")
Image_IDsToDelete = dr["Image_ID"].ToString();
else
Image_IDsToDelete = Image_IDsToDelete + "," + dr["Image_ID"].ToString();
if (NotUploadedFiles == "")
NotUploadedFiles = Convert.ToString(dr["FileName"]);//dr["Image_ID"] + dr["Extension"].ToString();
else
NotUploadedFiles = NotUploadedFiles + ", " + Convert.ToString(dr["FileName"]);
dr["Is_Uploaded"] = true;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
pbCtl.Is_WithError = true;
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), Global.Header, MessageBoxButtons.OK);
//pthread.Suspend();
}
}
finally
{
sm.Release();
}
}
It sounds like a producer / consumer queue is the structure you are looking for. Take a look a this answer and the others in the thread for examples of how to employ it.
I am using the following code to write a file to the Desktop.
string submittedFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
int i = 0;
StreamWriter sw = null;
sw = new StreamWriter(submittedFilePath, false);
for (i = 0; i < PSOLib.table.Columns.Count - 1; i++)
{
sw.Write(PSOLib.table.Columns[i].ColumnName + ";");
}
sw.Write(PSOLib.table.Columns[i].ColumnName);
sw.WriteLine();
foreach (DataRow row in PSOLib.table.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
sw.Write(array[i].ToString() + ";");
}
sw.Write(array[i].ToString());
sw.WriteLine();
}
sw.Close();
However whenever I try to invoke the method I get:
Access to the path 'C:\\Users\\User\\Desktop' is denied.
System.UnauthorizedAccessException.
You didn't specify a file for your StreamWriter, but a folder.
This should do it:
string submittedFilePath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\myFile.txt.";
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);
how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}
For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")