I'm trying to retrieve an image saved in postgresql database in BYTEA format, but I'm having difficulties in transforming the byte array to image using C#. I'm getting "INVALID PARAMETERS" as a return. I've been trying for days and still haven't been able to. Can anyone help me?
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();
}
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
using (MemoryStream mStream = new MemoryStream(byteArrayIn))
{
return Image.FromStream(mStream);
}
}
catch (Exception)
{
throw;
}
}
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();
dgv_empresa.Rows.Clear();
DataTable dados = new DataTable();
NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
adaptador.Fill(dados);
Image imagem = null;
if (dados.Rows.Count > 0)
{
foreach (DataRow linha in dados.Rows)
{
byte[] binary = ObjectToByteArray(linha[0]);
MemoryStream ms = new MemoryStream(binary, 0, binary.Length);
ms.Position = 0;
imagem = Image.FromStream(ms, true);
Image i = byteArrayToImage(binary);
}
}
pct_Imagem.Image = imagem;
}
catch (Exception ex)
{
conexao.Close();
MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
//dgv_empresa.Rows.Clear();
}
finally
{
conexao.Close();
}
}
Related
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
I have a digital signature problem with PDF files, the process is as follows:
- I have a PDF file on the Server, then I locate the signature and convert it to byte format [] with SHA1.
- The client will retrieve the signature from the USB token to assign to byte [] transmitted from the server.
- I then returned the server to assign the signature.
But when I code as below, the program still runs normally without error, but the USB signature contents are not signed into the pdf file. Please help me to fix it.
private void Form1_Load(object sender, EventArgs e)
{
string UnsingnedPdf = #"E:\PrintContractAdviceNote.pdf";
string TempPdf = #"E:\PrintContractAdviceNote_TMP.pdf";
string singnedPdf = #"E:\PrintContractAdviceNote_Sign.pdf";
PDFSigning cl = new PDFSigning();
cl.GetBytesToSign(UnsingnedPdf, TempPdf, singnedPdf, "CHUKY1", 3, "BIG BEAR");
}
public static X509Certificate2 selectCert()
{
X509Certificate2 certificate = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
if (store.Certificates.Count == 1)
{
//Return the certificate present.
certificate = store.Certificates[0];
}
else if (store.Certificates.Count > 0)
{
// Request the user to select a certificate
try
{
var certificates = X509Certificate2UI.SelectFromCollection(store.Certificates,
"Digital Certificates", "Select a certificate from the following list:",
X509SelectionFlag.SingleSelection);
// Check if one has been returned
if (certificates.Count == 1)
{
certificate = certificates[0];
var newCert = new X509Certificate2(certificate.RawData, "mypassword");
}
else
{
throw new ArgumentException("Please select a certificate to publish PnL to Flash");
}
}
catch (Exception ex)
{
}
}
else
{
throw new ArgumentException("There is no certificate available to publish PnL to flash, please contact support.");
}
}
finally
{
store.Close();
}
return certificate;
}
public class IpInfo
{
//country
public string Country { get; set; }
}
public byte[] GetBytesToSign(string unsignedPdf, string tempPdf, string signedPdf, string signatureFieldName, Int16 iType, string SignName)
{
if (File.Exists(tempPdf))
File.Delete(tempPdf);
if (File.Exists(signedPdf))
File.Delete(signedPdf);
byte[] array = null;
bool Islock = true;
FileStream os = File.OpenWrite(tempPdf);
PdfReader reader = new PdfReader(unsignedPdf);
DateTime dt = DateTime.Now;
using (PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'))
{
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Contact = "www.marico.com";
appearance.SignDate = dt;
//BaseFont bf = BaseFont.CreateFont(HttpContent.Current.Server.MapPath("~/Resources/Font/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Font font = new Font(bf, 8);
//appearance.Layer2Font = font;
appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
appearance.Acro6Layers = true;
appearance.Layer2Text = "Signed by:" + Environment.NewLine + " " + SignName + Environment.NewLine + "Date :" + Environment.NewLine + " " + dt.ToShortDateString() + " " + dt.ToShortTimeString();
Image img;
if (iType == 3)
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(15, 50, 235, 95), reader.NumberOfPages, signatureFieldName);
}
else
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 50, 570, 95), reader.NumberOfPages, signatureFieldName);
}
appearance.SignatureGraphic = img;
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.SignExternalContainer(appearance, external, 8192);
array = SHA1.Create().ComputeHash(appearance.GetRangeStream());
stamper.Dispose();
stamper.Close();
}
if (iType != 3)
{
while (Islock)
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
Islock = IsFileLocked(unsignedPdf);
}
}
else
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
X509Certificate2 cert = selectCert();
RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(cert.PrivateKey);
formatter.SetHashAlgorithm("SHA1");
byte[] signature = formatter.CreateSignature(array);
EmbedSignature(tempPdf, signedPdf, signatureFieldName, signature);
return (array);
}
public static bool IsFileLocked(string pathfile)
{
try
{
using (FileStream fs = new FileStream(pathfile, FileMode.Open))
{
fs.Dispose();
fs.Close();
}
return false;
}
catch (IOException ex)
{
return true;
}
}
private static void SetSigPosition(PdfSignatureAppearance sigAppearance, int oldSigCount, string signatureFieldName, int numpage = 1)
{
float llx = (200 + 20) * (oldSigCount % 5) + 20,
lly = (25 + 20) * (oldSigCount / 5) + 5,
urx = llx + 200,
ury = lly + 45;
}
public void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, byte[] signedBytes)
{
IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
using (FileStream os = File.OpenWrite(signedPdf))
{
using (PdfReader reader = new PdfReader(tempPdf))
{
MakeSignature.SignDeferred(reader, signatureFieldName, os, external);
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
}
}
private class MyExternalSignatureContainer : IExternalSignatureContainer
{
private readonly byte[] signedBytes;
public MyExternalSignatureContainer(byte[] signedBytes)
{
this.signedBytes = signedBytes;
}
public byte[] Sign(Stream data)
{
return signedBytes;
}
public void ModifySigningDictionary(PdfDictionary signDic)
{
}
}
So, I am trying to send an image between the server and client, however, somehow when the server receives the image, the image does not render all of it.
Client Side code:
//button click
Bitmap tImage = new Bitmap(#"C:\Users\Milan\Downloads\guitarstill.gif");
byte[] bStream;
//if (string.IsNullOrEmpty(tbPayload.Text)) return;
try
{
bStream = imageToByteArray(tImage);
if (mTcpClient != null)
{
if (mTcpClient.Client.Connected)
{
mTcpClient.GetStream().BeginWrite(imageToByteArray(tImage), 0, imageToByteArray(tImage).Length, onCompleteWriteToServer, mTcpClient);
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
//Within another method:
public byte[] imageToByteArray(System.Drawing.Image imageIn) {
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//richTextBox1.Text = ms.ToArray().ToString();
return ms.ToArray();
}
Server Side Code:
void onCompleteReadFromTCPClientStream(IAsyncResult iar)
{
TcpClient tcpc;
int nCountReadBytes = 0;
string strRecv;
ClientNode cn = null;
try
{
lock (mlClientSocks)
{
tcpc = (TcpClient)iar.AsyncState;
cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString());
nCountReadBytes = tcpc.GetStream().EndRead(iar);
if (nCountReadBytes == 0)// this happens when the client is disconnected
{
MessageBox.Show("Client disconnected.");
mlClientSocks.Remove(cn);
lbClients.Items.Remove(cn.ToString());
return;
}
strRecv = Encoding.ASCII.GetString(cn.Rx, 0, nCountReadBytes);
//strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes);
if (strRecv.StartsWith("GIF"))
{
//MemoryStream ms = new MemoryStream(cn.Rx);
//Image x = (Bitmap)((new ImageConverter()).ConvertFrom(cn.Rx));
pictureBox1.Image = byteArrayToImage(cn.Rx);
/*
lock (mlClientSocks)
{
//if (cn != null && cn.tclient != null && cn.tclient.Client.Connected)
//{
//foreach (var clients in spectatorsIPAndPort)
//{
cn = mlClientSocks.Find(x => x.strId == clients);
cn.Tx = new byte[512];
cn.Tx = Encoding.ASCII.GetBytes(strRecv);
cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient);
//Console.WriteLine("Sent Number of Clients via Request: " + Encoding.UTF8.GetString(cn.Tx) + " To " + clients);
//}
//}
}
*/
//printLine(DateTime.Now + " - " + cn.ToString() + ": " + strRecv);
}
cn.Rx = new byte[512];
tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
lock (mlClientSocks)
{
printLine("Client disconnected: " + cn.ToString());
mlClientSocks.Remove(cn);
lbClients.Items.Remove(cn.ToString());
}
}
}
//within another method
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn, 0, byteArrayIn.Length);
//ms.Position = 0;
Image returnImage = Image.FromStream(ms);
return returnImage;
}
My Output:
Expected output: - this full image
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;
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.