Memorystream object being passed to method doesn't contain values - c#

I am using a memorystream object to write values from streamwriter object into memory. I have several methods which are for logging errors and values so I pass my memorystream object between them as a parameter.
My problem is the memorystream doesn't contain values. See code below:
#region csvlogging
public static void initiateCsvLogging(SortedList<int, string> logList, SortedList<int, string> errorList) // Handles csv upload logging
{
logMsgError(errorList, logList);
}
public static void logMsgError(SortedList<int, string> errorList, SortedList<int, string> logList)
{
using (MemoryStream ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms);
try
{
sw.WriteLine("Errors:");
foreach (KeyValuePair<int, string> k in errorList)
{
if (k.Value == null)
{
sw.WriteLine("No errors reported.");
}
else
{
sw.WriteLine(k.Key + "," + k.Value);
}
}
}
catch (Exception ex)
{
}
finally
{
sw.WriteLine("");
}
logMsg(logList, ms);
}
} // Handles data upload error logging for csv
public static MemoryStream logMsg(SortedList<int, string> logList, MemoryStream ms)
{
string DateNow = System.DateTime.Now.Date.ToString("yyyy-MM-dd");
string FileName = "log " + DateNow + ".csv";
char[] delimiterChars = { ',' };
try
{
// Write values to textfile and save to Log folder
using (StreamWriter sw = new StreamWriter(ms))
{
if (logList.Keys.Count == 0)
{
sw.WriteLine("No new users added to Active Directory.");
}
else // If keys > 0 then new users have been added to AD
{
sw.WriteLine("Username" + "," + "Password" + "," + "Company" + "," + "Email");
foreach (KeyValuePair<int, string> k in logList)
{
string[] values = k.Value.Split(delimiterChars);
sw.WriteLine(values[0] + "," + values[1] + "," + values[2] + "," + values[3]);
}
}
try
{
sw.Flush();
sendLogByEmail(new MemoryStream(ms.ToArray()), FileName);
}
catch (Exception ex)
{
}
}
}
catch (ThreadAbortException ex)
{
}
finally
{
}
return ms;
} // Handles logging for csv
public static void sendLogByEmail(MemoryStream ms, string error, int count)
{
//Send mail by attachment code
SmtpClient smtpclient = new SmtpClient();
//smtpclient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//smtpclient.UseDefaultCredentials = true;
smtpclient.Host = "ldnmail";
MailMessage message = new MailMessage("nick.gowdy#orcinternational.co.uk", "nick.gowdy#orcinternational.co.uk");
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = error;
message.Attachments.Add(attach);
smtpclient.Send(message);
}
#endregion
Because I am not using the USING keyword do I have to write some more code for the memorystream object?

You have to flush (Close) the StreamWriter.
finally
{
sw.WriteLine("");
}
sw.Flush();
logMsg(logList, ms);
But in the end you use all data to send it by mail:
System.Net.Mime.ContentType ct = new
System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
It would seem a lot easier to collect the information in a StringBuilder through an attached StringWriter.
There are issues with a StreamWriter closing its Stream, that may be part of your problem.

Related

How to convert object in byte[] c#

CONVERT OBJECT TO BYTE[]
Hello how are you? I'm having difficulties in converting an object (returned by a query to the Postgres database) to byte[], I test in several different ways but I can't get the total size of the array stored in the database referring to the image. I have a single image saved in the database, and in each way I try to retrieve it, the byte[] comes with a different size depending on how I do the conversion from object to byte[]. The biggest array size I got was length = 42, the image has length = 675486. I've tried these ways.
using (conexao)
{
string sQL = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
using (var command = new NpgsqlCommand(sQL, conexao))
{
byte[] productImageByte = null;
conexao.Open();
var rdr = command.ExecuteReader();
while (rdr.Read())
{
productImageByte = (byte[])rdr[0];
}
rdr.Close();
if (productImageByte != null)
{
using (MemoryStream productImageStream = new MemoryStream(productImageByte))
{
ImageConverter imageConverter = new System.Drawing.ImageConverter();
pct_Imagem.Image = imageConverter.ConvertFrom(productImageByte) as System.Drawing.Image;
}
}
}
}
The result of this was length = 13
private void dgv_empresa_CellClick(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32(dgv_empresa.SelectedCells[0].OwningRow.Cells[9].Value);
if (id != 0)
{
try
{
string query = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
conexao.Open();
DataTable dados = new DataTable();
NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
adaptador.Fill(dados);
if (dados.Rows.Count > 0)
{
foreach (DataRow linha in dados.Rows)
{
byte[] data = ObjectToByteArray(linha[0]);
var imagem = (Image)new ImageConverter().ConvertFrom(data);
pct_Imagem.Image = imagem;
}
}
}
catch (Exception ex)
{
conexao.Close();
MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
conexao.Close();
}
}
}
byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
The result of this was length = 42
These last two brought me the best results. But still, it's not a valid byte array. Can someone help me?
you can use this method that I serialized the class into JSON text and then converted it to byte[]. You can either serialize it to XML
private byte[] CreateByteArray(object obj)
{
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
var jsonText = JsonConvert.SerializeObject(obj);
writer.WriteAsync(jsonText);
writer.Flush();
return memoryStream.ToArray();
}
I managed to do, what I needed to adjust to not use Connetion, but create and discard in each block that was to be used

XML Serialization leaves file blank after restart

We have a problem where our industrial equipments software's .XML settings files become blank, yet they still have the correct number of bytes.
I have a feeling it might be caused by the way the customers are shutting down the PC as it tends to happen after they've down a shutdown, isolate, and boot. The way I save the files is,
Serialize to %temp% file
Validate that the newly created file starts with <?xml
If the /backup folders version of the file is older than a day, copy the existing file to the /backup folder
Copy new file to overwrite existing file.
I thought maybe it's related to encoding, disk caching, Windows Update, or Windows Recovery.
Looking for ideas as I've spent two years chasing down why this is happening.
As per request, here is the code.
public static bool SerializeObjXml(object Object2Serialize, string FilePath, Type type, bool gzip = false)
{
if (!Path.IsPathRooted(FilePath))
FilePath = Path.Combine(ApplicationDir, FilePath);
bool isSuccess = false;
var tmpFile = Path.GetTempFileName();
try
{
for (int i = 0; i < 3; i++)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
if (gzip)
{
using (var ms = new MemoryStream())
{
XmlSerializer bf = new XmlSerializer(type);
bf.Serialize(ms, Object2Serialize);
ms.Position = 0;
using (var fileStream = new BinaryWriter(File.Open(tmpFile, FileMode.Create)))
{
using (GZipStream gzipStream = new GZipStream(fileStream.BaseStream, CompressionMode.Compress))
{
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = ms.Read(buffer, 0, buffer.Length)) != 0)
{
gzipStream.Write(buffer, 0, numRead);
}
}
}
}
if (!FileChecker.isGZip(tmpFile))
throw new XmlException("Failed to write valid XML file " + FilePath);
}
else
{
using (var fs = new StreamWriter(File.Open(tmpFile, FileMode.Create), Encoding.UTF8))
{
XmlSerializer bf = new XmlSerializer(type);
bf.Serialize(fs, Object2Serialize);
}
if (!FileChecker.isXML(tmpFile))
throw new XmlException("Failed to write valid XML file " + FilePath);
}
isSuccess = true;
return true;
}
catch (XmlException)
{
return false;
}
catch (System.IO.DriveNotFoundException) { continue; }
catch (System.IO.DirectoryNotFoundException) { continue; }
catch (System.IO.FileNotFoundException) { continue; }
catch (System.IO.IOException) { continue; }
}
}
finally
{
if (isSuccess)
{
lock (FilePath)
{
try
{
//Delete existing .bak file
if (File.Exists(FilePath + ".bak"))
{
File.SetAttributes(FilePath + ".bak", FileAttributes.Normal);
File.Delete(FilePath + ".bak");
}
}
catch { }
try
{
//Make copy of file as .bak
if (File.Exists(FilePath))
{
File.SetAttributes(FilePath, FileAttributes.Normal);
File.Copy(FilePath, FilePath + ".bak", true);
}
}
catch { }
try
{
//Copy the temp file to the target
File.Copy(tmpFile, FilePath, true);
//Delete .bak file if no error
if (File.Exists(FilePath + ".bak"))
File.Delete(FilePath + ".bak");
}
catch { }
}
}
try
{
//Delete the %temp% file
if (File.Exists(tmpFile))
File.Delete(tmpFile);
}
catch { }
}
return false;
}
public static class FileChecker
{
const string gzipSig = "1F-8B-08";
static string xmlSig = "EF-BB-BF";// <?x";
public static bool isGZip(string filepath)
{
return FileChecker.CheckSignature(filepath, (3, gzipSig)) != null;
}
public static bool isXML(string filepath)
{
return FileChecker.CheckSignature(filepath, (3, xmlSig)) != null;
}
public static bool isGZipOrXML(string filepath, out bool isGZip, out bool isXML)
{
var sig = FileChecker.CheckSignature(filepath, (3, gzipSig), (3, xmlSig));
isXML = (sig == xmlSig);
isGZip = (sig == gzipSig);
return isXML || isGZip;
}
public static string CheckSignature(string filepath, params (int signatureSize, string expectedSignature)[] pairs)
{
if (String.IsNullOrEmpty(filepath))
throw new ArgumentException("Must specify a filepath");
if (String.IsNullOrEmpty(pairs[0].expectedSignature))
throw new ArgumentException("Must specify a value for the expected file signature");
int signatureSize = 0;
foreach (var pair in pairs)
if (pair.signatureSize > signatureSize)
signatureSize = pair.signatureSize;
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (fs.Length < signatureSize)
return null;
byte[] signature = new byte[signatureSize];
int bytesRequired = signatureSize;
int index = 0;
while (bytesRequired > 0)
{
int bytesRead = fs.Read(signature, index, bytesRequired);
bytesRequired -= bytesRead;
index += bytesRead;
}
foreach (var pair in pairs)
{
string actualSignature = BitConverter.ToString(signature, 0, pair.signatureSize);
if (actualSignature == pair.expectedSignature)
return actualSignature;
}
}
return null;
}
}
Using the operating system's move or copy file to overwrite an existing file is an atomic operation meaning the it wholly succeeds or doesn't and doesn't overlap other file operations.
Therefore what you have should work if that is how you are achieving step 4.
Copy new file to overwrite existing file.
If instead you are blanking out the existing file and re-writing the data I suspect that could be the the point of failure..
The issues while file space is being allocated the write is not occurring during shutdown, which leaves you when a file with bytes allocated without the data being flushed to disk.
During the OS shutdown, likely a ThreadAbortException is raised which triggers your finally block.
You can attempt to reproduce by calling Process.Start("shutdown", "-a") before your return statement but after you have set success = true.
I would suggest simplifying your code and have everything run inside of your try {} statement. This removes the possibility of having a state where success = true before your attempted your write to disk, which is then triggered in a finally statement trigged by a windows shutdown.
public static bool SerializeObjXml(
object Object2Serialize,
string FilePath,
Type type,
bool gzip = false)
{
if (!Path.IsPathRooted(FilePath))
FilePath = Path.Combine(ApplicationDir, FilePath);
Directory.CreateDirectory(FilePath);
for (int i = 0; i < 3; i++)
{
try
{
var tempFi = SerializeToXmlFile(Object2Serialize, type, gzip);
var fi = new FileInfo(FilePath);
if (fi.Exists)
fi.CopyTo(fi.FullName + ".bak", true);
tempFi.CopyTo(fi.FullName, true);
tempFi.Delete();
return true;
}
catch (Exception ex)
{
string message = $"[{DateTime.Now}] Error serializing file {FilePath}. {ex}";
File.WriteAllText(FilePath + ".log", message);
}
}
return false;
}
As a side note, you can simply use [Stream.CopyTo][1] and write directly to your temp file, without the need for intermediary streams or for manual buffer/byte read/write operations:
private static FileInfo SerializeToXmlFile(
object Object2Serialize,
Type type,
bool gzip)
{
var tmpFile = Path.GetTempFileName();
var tempFi = new FileInfo(tmpFile);
if (!gzip)
{
using (var fs = File.Open(tmpFile, FileMode.Create))
(new XmlSerializer(type)).Serialize(fs, Object2Serialize);
if (!FileChecker.isXML(tmpFile))
throw new Exception($"Failed to write valid XML file: {tmpFile}");
}
else
{
using (var fs = File.Open(tmpFile, FileMode.CreateNew))
using (var gz = new GZipStream(fs, CompressionMode.Compress))
(new XmlSerializer(type)).Serialize(fs, Object2Serialize);
if (!FileChecker.isGZip(tmpFile))
throw new Exception($"Failed to write valid XML gz file: {tmpFile}");
}
return tempFi;
}

How to write and update a user score that is stored in a textfile in c#?

I am making a quiz game for my A level computing coursework. The quiz works fine, but the problem is that at the end of the quiz I want to save the users score and username to a text file. I have already tried to search for the answer both on Stack Overflow and other websites, but I couldn't find an answer.
At the end of the quiz I have a form called EndForm and when that form loads, I call a method called SaveScore(). The code is down below. I want this method to save the username and score of the user in the scores.txt file. I also want the users score to be updated if the user replays the quiz and gets a higher score. I don't know why my current code is not working.
private void SaveScore()
{
string file = #"..\..\textfiles\scores.txt";
FileStream fileStream;
StreamWriter streamWriter;
try
{
if (File.Exists(file))
{
string[] HighScore = File.ReadAllLines(file).ToArray();
string[] contents = new string[] { };
File.WriteAllLines(file, contents);
fileStream = new FileStream(file, FileMode.Create, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
for (int i = 0; i < HighScore.Length; i++)
{
string[] HighScores = HighScore[i].Split('~');
string username = HighScores[0];
int currentScore = Convert.ToInt32(HighScores[1]);
if (player.Score > currentScore)
{
streamWriter.WriteLine(player.Name + "~" + player.Score);
for (int x = i; x < 4; x++)
{
string[] newHighScore = HighScore[x].Split('~');
string newUsername = newHighScore[0];
int newScore = Convert.ToInt32(newHighScore[1]);
streamWriter.WriteLine(newUsername + "~" + newScore);
}
break;
}
else
{
streamWriter.WriteLine(username + "~" + currentScore);
}
streamWriter.Close();
fileStream.Close();
//Write player score data to file if it is not already there.
if (HighScore.Length < 10)
{
fileStream = new FileStream(file, FileMode.Append, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine(player.Name + "~" + player.Score);
streamWriter.Close();
fileStream.Close();
}
}
}
}
catch
{
MessageBox.Show("Error saving high score", "Error");
}
}
Any help would be appreciated, thanks in advance.
This should do everything you need - if you have any questions just ask. May I also suggest using a CSV rather than a text file? Simply change the extension.
private void SaveScore()
{
String scoresFilePath = #"..\..\textfiles\scores.txt";
try
{
//
// Create file if not exists
//
if (!File.Exists(scoresFilePath))
{
File.Create(scoresFilePath).Dispose();
}
//
// Create DataTable
//
DataColumn nameColumn = new DataColumn("name", typeof(String));
DataColumn scoreColumn = new DataColumn("score", typeof(int));
DataTable scores = new DataTable();
scores.Columns.Add(nameColumn);
scores.Columns.Add(scoreColumn);
//
// Read CSV and populate DataTable
//
using (StreamReader streamReader = new StreamReader(scoresFilePath))
{
streamReader.ReadLine();
while (!streamReader.EndOfStream)
{
String[] row = streamReader.ReadLine().Split(',');
scores.Rows.Add(row);
}
}
Boolean scoreFound = false;
//
// If user exists and new score is higher, update
//
foreach (DataRow score in scores.Rows)
{
if ((String)score["name"] == player.Name)
{
if ((int)score["score"] < player.Score)
{
score["score"] = player.Score;
}
scoreFound = true;
break;
}
}
//
// If user doesn't exist then add user/score
//
if (!scoreFound)
{
scores.Rows.Add(player.Name, player.Score);
}
//
// Write changes to CSV (empty then rewrite)
//
File.WriteAllText(scoresFilePath, string.Empty);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("name,score");
foreach (DataRow score in scores.Rows)
{
stringBuilder.AppendLine(score["name"] + "," + score["score"]);
}
File.WriteAllText(scoresFilePath, stringBuilder.ToString());
}
catch(Exception ex)
{
MessageBox.Show("Error saving high score:\n\n" + ex.ToString(), "Error");
}
}
Try not to swallow the exception and you should get a useful error message. Change:
catch
{
MessageBox.Show("Error saving high score", "Error");
}
to
catch(Exception ex)
{
MessageBox.Show("Error saving high score: " + ex.ToString(), "Error");
}

c# block length does not match with its complement

I am stuck with this error and I don't understand why. Can you help me out? I am trying to edit a PowerPoint file on a Sharepoint through the Client Object Model and OpenXML. The editing is working fine but for some reason I get thrown the block length does not match with its complementError. I have not yet found anything on google that helped.
Here is the Code in question:
class Program
{
// Credentials to log into the Sharepoint.
private static NetworkCredential credential = new NetworkCredential("login", "pwd", "domain");
static private void CopyStream(Stream source, Stream destination)
{
byte[] buffer = new byte[32768];
int bytesRead;
do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
destination.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
static void Main(string[] args)
{
try
{
// Creating the Clientcontext
ClientContext clientContext = new ClientContext("https://sharepoint.adress.com/folder/");
clientContext.Credentials = credential;
Web oWebsite = clientContext.Web;
// Collect all lists from Sharepoint.
ListCollection collList = oWebsite.Lists;
clientContext.Load(collList);
clientContext.ExecuteQuery();
Console.WriteLine("Connected to Sharepoint.");
// Getting the Presentation.
Console.WriteLine("Working on " + filename + "..");
Guid id = new Guid("2BBF9030-66C6-4F71-86E6-DFE41F57B9F3"); // List ID for the Slide Library.
List sharedDocumentsList = clientContext.Web.Lists.GetById(id);
CamlQuery camlQuery = new CamlQuery();
String queryString = "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + filename +
"</Value></Eq></Where><RowLimit>1</RowLimit></Query></View>"; // FileLeafRef is the column "name" on the Sharepoint.
camlQuery.ViewXml = #queryString;
ListItemCollection listItems = sharedDocumentsList.GetItems(camlQuery);
clientContext.Credentials = credential;
clientContext.Load(sharedDocumentsList);
clientContext.ExecuteQuery();
clientContext.Credentials = credential;
clientContext.Load(listItems);
clientContext.ExecuteQuery();
Console.WriteLine("Opened Document.");
if (listItems.Count == 1)
{
ListItem item = listItems[0];
clientContext.Credentials = credential;
FileInformation fileInformation = ClientOM.File.OpenBinaryDirect(clientContext, (string)item["FileRef"]);
using (MemoryStream memoryStream = new MemoryStream())
{
CopyStream(fileInformation.Stream, memoryStream);
using (PresentationDocument ppt = PresentationDocument.Open(memoryStream, true))
{
string rId = GetSlidePart(ppt, slideNumber - 1);
PresentationPart pptPart = ppt.PresentationPart;
SlidePart slide = (SlidePart)pptPart.GetPartById(rId);
Boolean exists = false;
//groupExists(slide.Slide, "IDGroup", exists);
if (!groupExists(slide.Slide, "IDGroup", exists))
{
Console.WriteLine(exists);
Console.WriteLine("IDGroup not found in " + filename + ", adding it..");
EditPresentation(memoryStream, clientContext, item);
}
else
{
Console.WriteLine(exists);
Console.WriteLine("IDGroup already exists, skipping Presentation..");
}
} // Error gets thrown here.
}
}
else
{
Console.WriteLine("Document not found.");
}
Console.WriteLine("Done.");
Console.Read();
}
catch (Exception ex) when (ex is ServerException || ex is InvalidCastException || ex is OpenXmlPackageException || ex is WebException)
{
Console.WriteLine(ex.ToString());
Console.Read();
}
}
And this is the Method that edits the File. Trimmed to the parts where I use the memoryStream, the full code can be viewed on pastebin:
public static void EditPresentation(MemoryStream memoryStream, ClientContext clientContext, ListItem item)
{
using (PresentationDocument ppt = PresentationDocument.Open(memoryStream, true))
{
string rId = GetSlidePart(ppt, slideNumber - 1);
PresentationPart pptPart = ppt.PresentationPart;
SlidePart slide = (SlidePart)pptPart.GetPartById(rId);
ShapeTree tree = new ShapeTree();
CommonSlideData commonSlideData1 = new CommonSlideData();
// 250 Lines of OpenXML go here.
slide.AddHyperlinkRelationship(new System.Uri(adress, System.UriKind.Absolute), true, "rId99");
slide.Slide.CommonSlideData.ShapeTree.Append(groupShape1);
slide.Slide.Save();
pptPart.Presentation.Save();
}
memoryStream.Seek(0, SeekOrigin.Begin);
ClientOM.File.SaveBinaryDirect(clientContext, (string)item["FileRef"], memoryStream, true);
}
Is there something fundamental I am doing wrong? I've never done anything like this and as always all suggestions for improvements would be appreciated.

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;

Categories