Multi attach files from DB row - c#

How I can't attach to splited string file name from DB row (I need for "mode = 2" and "case 2:").
In my log file error:
FILE TO ATTACH ERR : Could not find file
'C:\inetpub\wwwroot\PLATFORM_700_NTFSRV\PLATFORM_700_NTFSRV_LAB\Attachments\text.txt,text2.txt'.
Here my example code and my row in DB
Row in db:
|FILE_TO_ATTACH |
|text1.txt,text2.txt|
public DataTable GetAttachmentFiles(int mode , string fileIDList)
{
try
{
DataTable DTB = new DataTable();
if (mode == 1)
{
SqlCommand TheCommand = GetCommand("application_MessageAttachFiles", CommandType.StoredProcedure,
GetConnection("APP"));
TheCommand.Parameters.Add("FILEIDLIST", SqlDbType.VarChar, 8000);
TheCommand.Parameters["FILEIDLIST"].Value = fileIDList;
SqlDataAdapter SDA = new SqlDataAdapter();
SDA.SelectCommand = TheCommand;
SDA.Fill(DTB);
}
else if(mode == 2)
{
try
{
DTB.Columns.Add("FILENAME");
string[] fileList = fileIDList.Split(',');
for (int c = 0; c < fileList.Length; c++)
{
DataRow DR = DTB.NewRow();
DR["FILENAME"] = fileList[c];
DTB.Rows.Add(DR);
}
}
catch (Exception ex)
{
RecordLine("ERROR Reading GetAttachmentFiles: " + ex.Message);
}
}
return DTB;
}
catch (Exception eX)
{
RecordLine("ERROR GetAttachmentFiles : " + eX.Message);
return null;
}
}
public Attachment AttachmentFile(int mode, string fileNameString, int fileID, DataRow DRA)
{
// mode.ToString(ConfigurationSettings.AppSettings["MODE"]);
try
{
switch (mode)
{
case 1: /*from Database*/
if (DRA != null)
{
Attachment messageAttachment;
int fileDataSize = int.Parse(DRA["FileSize"].ToString());
string fileType = DRA["FileType"].ToString();
string fileName = DRA["FileName"].ToString();
byte[] fileBuffer = (DRA["FileData"]) as byte[];
MemoryStream ms = new MemoryStream(fileBuffer);
RecordLine("DEBUG 2 - " + fileName + " " + fileType + " " + fileDataSize.ToString() + " " + ms.Length.ToString() + " buffer size:" + fileBuffer.Length.ToString());
messageAttachment = new Attachment(ms, fileName, fileType);
return messageAttachment;
}
break;
case 2: /*from Local Machin */
{
Attachment messageAttachment;
try
{
fileNameString = String.Format("{0}\\{1}", ConfigurationSettings.AppSettings["SOURCE_FILE"],
fileNameString);
messageAttachment = new Attachment(fileNameString);
RecordLine("DEBUG 2.1 - " + messageAttachment.Name);
return messageAttachment;
}
catch (Exception ex)
{
RecordLine("FILE TO ATTACH ERR : " + ex.Message);
}
}
break;
default:
return null;
break;
}
return null;
}
catch (Exception eX)
{
RecordLine("ERROR AttachmentFile : " + eX.Message);
return null;
}
}

I had add this code and it is worked:
foreach (DataRow DRA in DTBA.Rows)
{
message.Attachments.Add(AttachmentFile(2, DRA["FILENAME"].ToString().Trim(), 0, null));
RecordLine("DEBUG 3.1 - " + message.Attachments.Count.ToString());
}

Related

return File (memory stream) encoding

Hi I have problem to return right encoded file.
finalString is here only for my control of encoding and show me right strings, but returned excel file dont contain right czech characters... (Č č š Š Ž etc...) Can someone help me?
byte[] bytes = encode.GetBytes(str.ToString());
string finalString = encode.GetString(bytes);
Here is complete class:
public async Task<IActionResult> ExportExcel()
{
// List<Material> obj = new List<Material>();
// obj = await _context.Material.ToListAsync();
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
str.Append("<td><b>Id</b></td>");
str.Append("<td><b>Name</b></td>");
str.Append("</tr>");
// foreach (Material val in obj)
// {
str.Append("<tr>");
str.Append("<td>" + "0" + "</td>");
str.Append("<td>" + Česnek + "</td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Name.ToString() + "</font></td>");
str.Append("</tr>");
// }
str.Append("</table>");
string uc = Configuration.UserCulture;
int codepage = 1250; // _cultureDataProvider.GetAnsiCodePage(uc);
Encoding encode = Encoding.GetEncoding(codepage);
byte[] bytes = encode.GetBytes(str.ToString());
string finalString = encode.GetString(bytes);
MemoryStream stream = new MemoryStream(bytes);
return File(stream, "application/vnd.ms-excel", "excel.xls");
/*
HttpContext.Response.Headers.Add("content-disposition", "attachment; filename=Information" + DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] temp = System.Text.Encoding.ASCII.GetBytes(str.ToString());
return File(temp, "application/vnd.ms-excel");
*/
}
I was able to solve it after one day - csv and tab .txt file solution: (working under Core CLR)
public async Task<IActionResult> Export(string type)
{
string _OuputType = type.ToLower().Trim();
string _delimiter = _OuputType.Contains("csv") ? ";" : String.Empty;
_delimiter = _OuputType.Contains("txt") ? "" : _delimiter;
IEnumerable<Material> data = await _context.Material.Include(m => m.Unit).ToListAsync();
StringBuilder str = new StringBuilder();
//file name
string fileName = "Material-" + DateTime.Now.ToString("dd_MM_yyyy-H_mm_ss");
//head
str.Append("Name" + _delimiter + "\t");
str.Append("AutoPlan" + _delimiter + "\t");
str.Append("QuantityMinStock" + _delimiter + "\t");
str.Append("QuantityMaxStock" + _delimiter + "\t");
str.Append("QuantityPurchase" + _delimiter + "\t");
str.Append("Unit" + _delimiter + "\t");
str.Append("\r\n");
//data
foreach (Material m in data)
{
str.Append(m.id + _delimiter + "\t");
str.Append(m.Name + _delimiter + "\t");
str.Append(m.AutoPlan + _delimiter + "\t");
str.Append(m.QuantityMinStock + _delimiter + "\t");
str.Append(m.QuantityMaxStock + _delimiter + "\t");
str.Append(m.QuantityPurchase + _delimiter + "\t");
str.Append(m.Unit.LocalizedCode + _delimiter + "\t");
str.Append("\r\n");
}
// int codepage = _cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture); == This is my service to get code page (example: 1250, or 1252 etc...)
Encoding encode = Encoding.GetEncoding(_cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture));
byte[] bytes = encode.GetBytes(str.ToString());
if (_OuputType == "txt"){return File(bytes, "text/plain", fileName + ".txt");}
return File(bytes, "application/msexcel", fileName + ".csv");
}
ANSI does not provide valid encoding for Č, č, š, Š, Ž you should look for more suitable codepages like UTF-8, UTF-16, UTF-32, etc....
byte[] bytes = Encoding.UTF8.GetBytes(str.ToString());
string finalString = Encoding.UTF8.GetString(bytes);
Did you try to work using Office Interop? It would be more ease and right way to work with Excel.
Here is simple worksheet manager
public class ExcelManager
{
public ExcelManager()
{
ItsApplication = null;
ItsWorkbook = null;
ItsWorksheet = null;
AppInitialization = false;
WrbInitialization = false;
WrsInitialization = false;
}
/*////////////////////////////////////////////////////*/
public void Initialize(bool visible)
{
try
{
if (ItsApplication == null)
{
ItsApplication = new Microsoft.Office.Interop.Excel.Application();
ItsApplication.SheetsInNewWorkbook = 1;
ItsApplication.Visible = visible;
AppInitialization = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CreateWorkbook()
{
try
{
if (ApplicationInitialized)
{
ItsWorkbook = ItsApplication.Workbooks.Add(MissingValue);
WrbInitialization = true;
}
else
MessageBox.Show(
"Couldnot create workbook!\n" +
"App instance didnot initialized!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CreateWorksheet()
{
try
{
if (WorkbookInitialized)
{
ItsWorksheet = ItsWorkbook.Worksheets.Add(MissingValue,
MissingValue, MissingValue, MissingValue);
WrsInitialization = true;
CurrentRow = 1;
}
else
MessageBox.Show(
"Couldnot create worksheet!\n" +
"Workbook didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SetText(string text,int bold,int italic,int cells_offset)
{
try
{
if (WorksheetInitialized)
{
ArrayList lines_list = new ArrayList();
string curr_line = "";
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n' || (i == text.Length - 1))
{
lines_list.Add(curr_line);
curr_line = "";
}
curr_line += text[i];
}
CurrentRow += cells_offset;
foreach (object line in lines_list)
{
Range text_range =
ItsWorksheet.get_Range("A" + CurrentRow, "A" + CurrentRow);
text_range.Font.Bold = bold;
text_range.Font.Italic = italic;
text_range.Value2 = line;
text_range.WrapText = false;
CurrentRow++;
}
}
else
MessageBox.Show(
MessageBox.Show(
"Cannot output any text!\n" +
"Worksheed didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SetData(System.Data.DataTable table, int bold, int italic,int rows_offset)
{
try
{
if (WorksheetInitialized)
{
CurrentRow += rows_offset;
int TableRows = table.Rows.Count;
int TableCols = table.Columns.Count;
char ACol = 'A';
Range TableRange = ItsWorksheet.get_Range("A" + CurrentRow,
((char)((int)ACol + TableCols - 1)).ToString() + (CurrentRow + TableRows).ToString());
TableRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
for (int i = 0; i < TableCols; i++)
{
Range names_range = ItsWorksheet.get_Range(((char)((int)ACol + i)).ToString() + CurrentRow,
((char)((int)ACol + i)).ToString() + CurrentRow);
names_range.Value2 = table.Columns[i].ColumnName;
}
for (int i = 1; i < TableRows + 1; i++)
{
for (int j = 0; j < TableCols; j++)
{
Range cell_range = ItsWorksheet.get_Range(((char)((int)ACol + j)).ToString() + (CurrentRow + i),
((char)((int)ACol + j)).ToString() + (CurrentRow + i));
cell_range.Value2 = table.Rows[i - 1].ItemArray[j];
cell_range.Font.Bold = bold;
cell_range.Font.Italic = italic;
}
}
CurrentRow += TableRows;
}
else
MessageBox.Show(
"Cannot output any text!\n" +
"Worksheed didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SaveCurrentWorksheet(string filename)
{
try
{
ItsWorksheet.SaveAs(filename,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CloseCurrentWorksheet()
{
if (WorkbookInitialized)
{
ItsWorkbook.Close(MissingValue,
MissingValue,
MissingValue);
ItsApplication.Quit();
WrbInitialization = false;
WrsInitialization = false;
AppInitialization = false;
}
}
public bool ApplicationInitialized
{
get
{
return AppInitialization;
}
}
public bool WorkbookInitialized
{
get
{
return WrbInitialization;
}
}
public bool WorksheetInitialized
{
get
{
return WrsInitialization;
}
}
////////////////////////////////////////////////////////
private _Application ItsApplication;
private _Worksheet ItsWorksheet;
private _Workbook ItsWorkbook;
// Initialization flags
private bool AppInitialization;
private bool WrbInitialization;
private bool WrsInitialization;
// Positioning text in rows
private int CurrentRow;
////////////////////////////////////////////////////////
// Define static members of class
private static object MissingValue = System.Reflection.Missing.Value;
private static object EndOfDocument = "\\endofdoc";
}
You can use SetData method to print tables to excel files.
Simple instruction:
Create instance of class;
Initialize world application by calling public void Initialize(bool visible) visible controll the wisibility of Excell window.
Create new workbook by calling CreateWorkbok;
And worksheet by CreateWorksheet;
Work with worksheet SetData - prints table DataTable;
Work with text SetText.
To save and close use SaveCurrentWorksheet and CloseCurrentWorksheet.
ExcelManager excel_manager = new ExcelManager()
excel_manager.Initialize(true);
excel_manager.CreateWorkbook();
excel_manager.CreateWorksheet();
excel_manager.SetText("Česnek!", 1, 0, 0);
excel_manager.SetData(systemTable, 0, 0, 2);
excel_manager.SetText("Лог консолі!", 1, 0, 3);
The result of calls:
Or you can use Open XML SDK for Office, to support multitask in your web application.

XMLNodeList null reference even after checking the next innertext value in advance

I am trying to get the value from the next item, for example, if the next item is null, or doesnt exist, it will proceed to printing. The main problem i am having lies only at this part
Main Question :
try
{
numCheck = productList[j+1]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
if (numCheck != null)
{
try
{
mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I did a check before i tried if else just to make sure the value exist, however, even after it detects that it has a value, this line will throw an error NullReference
mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText);
FULL Code just in case:
XmlDocument xml = new XmlDocument();
xml.LoadXml(productItems);
XmlNodeList productList = xml.SelectNodes("/Products/Product");
for (int j = 0; j < productList.Count; j++)
{
itemCount++;
int i = j + 1;
string item = productList[j]["Number"].InnerText;
number = Data.getFullItemDetail(item);
try
{
#region mainItem
if (number == 0)
{
itemCount++;
itemName = productList[j]["Name"].InnerText;
try
{
numCheck = productList[i]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
if (numCheck != null)
{
try
{
mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (mainNumber == 0)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
else
{
MessageBox.Show("Error");
}
}
else
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
}
}
#endregion
#region CondimentItem
else if (number == 4)
{
condiment.Add(productList[j]["Name"].InnerText);
try
{
numCheck = productList[i]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
//Check next item.
if (numCheck == null)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
}
else
{
mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText);
if (mainNumber == 0)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
}
}
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Edited : Data.getFullItemDetail only returns 1 int value.
public static int getFullItemDetail(string number)
{
int num = Convert.ToInt32(number);
int numReturn;
using (SqlConnection conn = getConnectionSAP())
{
SqlCommand comm = new SqlCommand("select belongcond from ------ where number = " + num, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
num = Convert.ToInt32(dr["-------"]);
}
comm.Clone();
comm.Dispose();
}
num = Convert.ToInt32(num.ToString().Substring(0, 1));
return num;
}
productList[j+1]["Number"] is null, so at the second line an exception is thrown (because you can't call null.InnerText), caught and then you set numCheck = string.Empty.
The next line you test for if (numCheck != null), which is true, because you just set it to string.Empty in the exception handler. You then call InnerText on productList[j+1]["Number"] again, which throws a NullReferenceException again.
Set breakpoints, walk through your code, inspect your variables, just as explained in What is a NullReferenceException and how do I fix it?.
Just change your if (numCheck != null) to if (productList[j+1]["Number"] != null).

How to return a value from string function

I have this code and I want to return a value Lidoc_num, but I got an error
"not all code paths return a value"....can someone solve this, please
public string Dohvati_IDOC()
{
try
{
//Spoji se na Oracl
SpajanjeNaOracle();
//Postavi transakcijski objekt kroz koji ćeš izvršiti PL/SQL proceduru - ORACLE baza podataka
com1.Connection = ora_cn;
com1.CommandType = CommandType.Text;
//-- PRIPREMA TRANSAKCIJE NA ORACLE-u
ora_trn = ora_cn.BeginTransaction(IsolationLevel.ReadCommitted);
com1.CommandType = CommandType.StoredProcedure;
com1.Transaction = ora_trn;
//Učitavanje parametara za dohvat broja idoc-a
foreach (DataRow dr_art_apa in ds.Tables["Agr3PLInventoryTransaction"].Rows)
{
//Provjera učitava li se dokument ili artikl
////Izlazni parametra iz funkcije - > Broj dokumenta
System.Data.OracleClient.OracleParameter prm = new System.Data.OracleClient.OracleParameter();
prm.Direction = ParameterDirection.ReturnValue;
prm.DbType = DbType.AnsiString;
prm.Size = 16;
com1.Parameters.Add(prm);
msg_type = ds.Tables["Header"].Rows[0]["MessageType"].ToString();
sender = ds.Tables["Sender"].Rows[0]["LogicalId"].ToString();
sender = sender.Length > 17 ? sender.Substring(0, 17) : sender;
reciver = ds.Tables["Receiver"].Rows[0]["LogicalId"].ToString();
reciver = reciver.Length > 17 ? reciver.Substring(0, 17) : reciver;
string var_date = ds.Tables["ApplicationArea"].Rows[0]["CreationDateTime"].ToString();
DateTime dt = DateTime.Parse(var_date);
cre_date = dt.ToString("dd.MM.yyyy");
bod_ID = ds.Tables["ApplicationArea"].Rows[0]["BODId"].ToString();
bod_ID = bod_ID.Length > 22 ? bod_ID.Substring(0, 21) : bod_ID;
//Predaj parametre funkciji i vrati broj dokumenta iz baze
com1.CommandText = "TRB01.set_idoc('" + msg_type + "','1','"
+ sender + "','"
+ reciver + "','"
+ cre_date + "','"
+ bod_ID + "')";
com1.ExecuteNonQuery();
Lidoc_num = com1.Parameters[0].Value.ToString();
}
return Lidoc_num;
}
catch (OracleException ex)
{
if (ora_trn != null) ora_trn.Rollback();
if (ora_cn != null)
if (ora_cn.State != ConnectionState.Closed)
ora_cn.Close();
WriteErrors.WriteToLogFile("Dohvati_IDOC", "Greška:" + ex.ToString());
}
}
If an error is trapped before the return, it'll bounce to the catch block, then fall off the end without a return value. You need a return after the catch block.
Just add return at your catch or add a return result as string
string result = string.Empty;
try
{
// code here
Lidoc_num = com1.Parameters[0].Value.ToString();
result = Lidoc_num;
}
catch (OracleException ex)
{
if (ora_trn != null) ora_trn.Rollback();
if (ora_cn != null)
if (ora_cn.State != ConnectionState.Closed)
ora_cn.Close();
WriteErrors.WriteToLogFile("Dohvati_IDOC", "Greška:" + ex.ToString());
result = "";
}
return result;
What if there is an exception. Code goes in catch, but you do not return anything from there.
Add a return statement in catch like return String.Empty or return null.
and where it is called you can check like this
if(!String.IsNullOrEmpty(Dohvati_IDOC()))
{
//Code here
}
else
{
//Code here
}

how to save exception in txt file?

public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
DataTable GetListID = new DataTable();
try
{
SqlParameter[] arParams = new SqlParameter[4];
arParams[0] = new SqlParameter("#Date", typeof(DateTime));
arParams[0].Value = objFeedRetPL.requestdate;
}
catch (Exception ex)
{
string dir = #"C:\Error.txt"; // folder location
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
File.AppendAllText(Server.MapPath("~/Error.txt"), New);
}
}
}
Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In
C drive Error.txt
Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:
string filePath = #"C:\Error.txt";
Exception ex = ...
using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
writer.WriteLine( "-----------------------------------------------------------------------------" );
writer.WriteLine( "Date : " + DateTime.Now.ToString() );
writer.WriteLine();
while( ex != null )
{
writer.WriteLine( ex.GetType().FullName );
writer.WriteLine( "Message : " + ex.Message );
writer.WriteLine( "StackTrace : " + ex.StackTrace );
ex = ex.InnerException;
}
}
The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErrorLoggingSample
{
class Program
{
static void Main(string[] args)
{
try
{
string str = string.Empty;
if (string.IsNullOrEmpty(str))
{
throw new Exception("Wrong Data");
}
}
catch (Exception ex)
{
ErrorLogging(ex);
ReadError();
}
}
public static void ErrorLogging(Exception ex)
{
string strPath = #"D:\Rekha\Log.txt";
if (!File.Exists(strPath))
{
File.Create(strPath).Dispose();
}
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error Logging ===========");
sw.WriteLine("===========Start============= " + DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
sw.WriteLine("===========End============= " + DateTime.Now);
}
}
public static void ReadError()
{
string strPath = #"D:\Rekha\Log.txt";
using (StreamReader sr = new StreamReader(strPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
I use that one
catch (Exception e)
{
new MessageWriteToFile(e).WriteToFile();
}
public class MessageWriteToFile
{
private const string Directory = "C:\\AppLogs";
public string Message { get; set; }
public Exception Exception { get; set; }
public string DefaultPath
{
get
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var folder = $"{Directory}\\{appName}";
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
return $"{Directory}\\{appName}\\{fileName}";
}
}
public MessageWriteToFile(string message)
{
Message = message;
}
public MessageWriteToFile(Exception ex)
{
Exception = ex;
}
public bool WriteToFile(string path = "")
{
if (string.IsNullOrEmpty(path))
{
path = DefaultPath;
}
try
{
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
writer.WriteLine();
if (Exception != null)
{
writer.WriteLine(Exception.GetType().FullName);
writer.WriteLine("Source : " + Exception.Source);
writer.WriteLine("Message : " + Exception.Message);
writer.WriteLine("StackTrace : " + Exception.StackTrace);
writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
}
if (!string.IsNullOrEmpty(Message))
{
writer.WriteLine(Message);
}
writer.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
}
Try This
try
{
int i = int.Parse("Prashant");
}
catch (Exception ex)
{
this.LogError(ex);
}
private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(message);
writer.Close();
}
}
string[] path1 = Directory.GetFiles(#"E:\storage", "*.txt");//it get the all textfiles from the folder
for (var i = 0; i < path1.Length; i++)
{
var file = Directory.GetDirectories(networkPath);
var path = file;
string temp_FilePath = "E:\\temp.txt";
string temp_FilePath1 = #"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
string temp_FilePath2 = #"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
string folder = #"E:\ExceptionFiles\Cs_regular";
string folder1 = #"E:\ExceptionFiles\CC_eBilling";
string[] lines;
var list = new List<string>();
var list1 = new List<string>();
var list2 = new List<string>();
var error = false;
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
var timenow1 = "2020/10/31 10:11";
if (res == timenow1)
{
string linesRemoved = "ERROR";
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list1.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if (line.Contains("Exception1") && error == false)
{
list1.Add(line);
error = true;
}
}
}
}
using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
{
string line;
while ((line = streamReader2.ReadLine()) != null)
{
string linesRemoved = "ERROR";
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
var timenow1 = "2020/10/29 12:38";
if (res == timenow1)
{
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list2.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
{
list2.Add(line);
error = true;
}
}
}
}
if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
{
int fileCount = Directory.GetFiles(folder).Length;
int fileCount1 = Directory.GetFiles(folder1).Length;
fileCount++;
fileCount1++;
temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";
}
{
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
System.IO.File.WriteAllLines(temp_FilePath, list);
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
}
}
catch (Exception ex)
{
}
return null;

Folder Watch when File is Created

im writing a code in C# that watches a folder and when a file gets created the code makes some actions and writes the results to a log file.
im having this very strange behaviour. when i file gets created in the watched folder the function that handles the change is executed twise! even if it is only one change event.
initially i used FileSystemWatcher. but i after looking it up, i saw that it has meny stability issued so i switched to MyFileSystemWatcher which is a much more stable impliminatation. but im still getting duplications in my log file. i have no idea why the code that is in chanrge for looking up the change runs twise. here is the code sample
protected void Folder_Watch(string path)
{
if (!Directory.Exists(path))
{
try
{
System.IO.Directory.CreateDirectory(path);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error: " + ex.Message.ToString() + Environment.NewLine);
}
}
MyFileSystemWatcher m_Watcher = new MyFileSystemWatcher(path);
//m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = NotifyFilters.FileName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
here is the onChange function
private void OnChanged(object source, FileSystemEventArgs e)
{
File.AppendAllText(logPath + "\\SSHConnectionLog.log", "[]*******" + DateTime.Now + " OnChanged function: " + Environment.NewLine);
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
//PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
//ScpClient client = new ScpClient("remnux", "adi", PKey);
Chilkat.SFtp client = new Chilkat.SFtp();
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function: " + ex.Message.ToString() + Environment.NewLine);
}
}
}
any help would be very much appriciated!
handled the onChange function. added time and file name to handle duplicate hits
private void OnChanged(object source, FileSystemEventArgs e)
{
string[] temp = new string[3];
string[] tempNow = new string[3];
string[] tempSeconds = new string[2];
string[] tempNowSeconds = new string[2];
int temp1 = 0;
int temp2 = 0;
if(string.IsNullOrEmpty(changeName))
{
changeName = e.Name;
}
if (string.IsNullOrEmpty(changeTime))
{
changeTime = DateTime.Now.ToString();
temp = this.changeTime.Split(':');
tempNow = DateTime.Now.ToString().Split(':');
tempSeconds = temp[2].Split(' ');
tempNowSeconds = temp[2].Split(' ');
temp1 = Convert.ToInt16(tempSeconds[0]);
temp2 = Convert.ToInt16(tempNowSeconds[0]);
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
ScpClient client = new ScpClient("remnux", "adi", PKey);
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function: " + ex.Message.ToString() + Environment.NewLine);
}
}
}
if (!this.changeTime.Equals(DateTime.Now.ToString()))
{
temp = this.changeTime.Split(':');
tempNow = DateTime.Now.ToString().Split(':');
tempSeconds = temp[2].Split(' ');
tempNowSeconds = temp[2].Split(' ');
temp1 = Convert.ToInt16(tempSeconds[0]);
temp2 = Convert.ToInt16(tempNowSeconds[0]);
if (temp[2] != tempNow[2])
{
if ((temp1 < temp2 + 10 || temp1 > temp2 +40) && e.Name != changeName)
{
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
ScpClient client = new ScpClient("remnux", "adi", PKey);
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function(second if): " + ex.Message.ToString() + Environment.NewLine);
}
}
}
}
}
}

Categories