return File (memory stream) encoding - c#

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.

Related

Why when giving files names numbers to the names using a counter it's giving it strange numbers?

The first saved file name on the hard disk is: 201701311645---0 then 201701311645---1 then 201701311645---20 then 201701311645---21 then 201701311645---40 and 201701311645---41
But i want it to be saved as: 201701311645---0 then 201701311645---1 then 201701311645---2 then 201701311645---3 then 201701311645---4 and 201701311645---5
In the top i added a counter variable
private int countFilesNames = 0;
Then in a dowork event i also reset the counter to 0 once so if i start the backgroundworker over again it will start from 0.
private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
{
Int32 fileNr = 0;
countFilesNames = 0;
if (this.SupportsProgress) { calculateFilesSize(); }
if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }
while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
{
m_fileNr = fileNr;
downloadFile(fileNr);
if (bgwDownloader.CancellationPending)
{
fireEventFromBgw(Event.DeletingFilesAfterCancel);
cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
}
else
{
fileNr += 1;
}
}
}
Then in the downloadFile method
private void downloadFile(Int32 fileNr)
{
FileStream writer = null;
m_currentFileSize = 0;
fireEventFromBgw(Event.FileDownloadAttempting);
FileInfo file = this.Files[fileNr];
Int64 size = 0;
Byte[] readBytes = new Byte[this.PackageSize];
Int32 currentPackageSize;
System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
Int32 readings = 0;
Exception exc = null;
try
{
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames + ".png", System.IO.FileMode.Create);
}
catch(Exception err)
{
string ggg = err.ToString();
}
HttpWebRequest webReq;
HttpWebResponse webResp = null;
try
{
webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
webResp = (HttpWebResponse)webReq.GetResponse();
size = webResp.ContentLength;
}
catch (Exception ex) { exc = ex; }
m_currentFileSize = size;
fireEventFromBgw(Event.FileDownloadStarted);
if (exc != null)
{
bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
}
else
{
m_currentFileProgress = 0;
while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
{
while (this.IsPaused) { System.Threading.Thread.Sleep(100); }
speedTimer.Start();
currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);
m_currentFileProgress += currentPackageSize;
m_totalProgress += currentPackageSize;
fireEventFromBgw(Event.ProgressChanged);
writer.Write(readBytes, 0, currentPackageSize);
readings += 1;
if (readings >= this.StopWatchCyclesAmount)
{
m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
speedTimer.Reset();
readings = 0;
}
}
speedTimer.Stop();
writer.Close();
webResp.Close();
if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
}
fireEventFromBgw(Event.FileDownloadStopped);
countFilesNames += 1;
}
I build the file name:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames + ".png", System.IO.FileMode.Create);
The move the counter forward by 1:
countFilesNames += 1;
But i'm getting other files names then i wanted.
Maybe there is a better way to give the files names some identity ? The problem is that if i will not give the files names some identity it will overwrite the files all the time. The files names are the same the content is not so i need to give each file another name.
Why don't you just increment the counter only when a file is written (since the variable doesn't look like it is accessed elsewhere) and not below:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames++ + ".png", System.IO.FileMode.Create);
This way the counter won't be incremented on errors.

How to ignore protected pdf's?

I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}

Memory usage is growing while processing files

I'm developing an application that reads a xml file folder , and each file it to do some checks and copied to a new folder based on some criteria.
But memory usage continues to grow when it arrives in the foreach loop , and I believe that should not happen , because the variables do not increase at each iteration , are only overwritten.
Here is my code:
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
namespace XMLOrganizer
{
public partial class Form1 : Form
{
string selectedFolder;
public Form1()
{
InitializeComponent();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
selectedFolder = folderBrowserDialog1.SelectedPath;
organizeBtn.Enabled = true;
}
private void organizeBtn_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Selecione o tipo de nota", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
return;
}
if (comboBox1.SelectedIndex != 2)
{
OrganizeXml(label2, selectedFolder, comboBox1);
}
//ORGANIZAR LOTES
else
{
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int atualFile = 1, totalXML = files.Length;
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(file);
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
string versao = ((XmlElement)enviNFe[0]).Attributes["versao"].Value;
XmlNodeList NFe = ((XmlElement)enviNFe[0]).GetElementsByTagName("NFe");
Directory.CreateDirectory(selectedFolder + #"\NOTAS");
label2.Text = "Processando arquivo " + atualFile + " de " + totalXML;
string notaXML;
foreach (XmlElement nota in NFe)
{
notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao + "\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml + "</nfeProc>";
XmlNodeList infNFe = nota.GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
File.WriteAllText(selectedFolder + "\\NOTAS\\" + chave + ".xml", notaXML);
}
}
OrganizeXml(label2, selectedFolder + "\\NOTAS", comboBox1);
}
}
private static void OrganizeXml(Label label2, string selectedFolder, ComboBox comboBox1)
{
string folderMove = String.Empty;
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int i = 1, arquivos = files.Length;
Directory.CreateDirectory(folder + #"\ORGANIZADO");
if (comboBox1.SelectedIndex != 2)
{
Directory.CreateDirectory(folder + #"\ORGANIZADO\OUTROS");
Directory.CreateDirectory(folder + #"\ORGANIZADO\LOTES");
}
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
try
{
xmlDocument.Load(file);
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
var nota = ((XmlElement) NFe[0]);
if (nota != null)
{
XmlNodeList infNFe = ((XmlElement) NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
string versao = infNFe[0].Attributes["versao"].Value;
string notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao +
"\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml +
"</nfeProc>";
string dirNote = Path.GetDirectoryName(file);
File.WriteAllText(dirNote + "\\fix_" + chave + ".xml", notaXML);
}
}
//
//
//
}
catch (XmlException)
{
XmlDocument doc = new XmlDocument();
string arquivo = ReadFileToString(file);
arquivo = RemoveSpecialCharacters(arquivo);
if (arquivo == "")
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
continue;
}
try
{
doc.LoadXml(arquivo);
doc.PreserveWhitespace = true;
doc.Save(file);
}
catch (XmlException)
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
files = files.Where(f => f != file).ToArray();
}
}
}
foreach (string file in files)
{
string arquivoLoad = file;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(arquivoLoad);
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
if (NFe.Count == 0)
{
if (File.Exists(folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad,
folder + #"\ORGANIZADO\OUTROS\no_NFe_" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad));
}
continue;
}
XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
File.Move(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_nfeProc_" + Path.GetFileName(arquivoLoad));
arquivoLoad = Path.GetDirectoryName(file) + "\\fix_" + chave + ".xml";
}
if (enviNFe.Count > 0)
{
if (File.Exists(folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad));
}
continue;
}
//XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
XmlNodeList ide = ((XmlElement)infNFe[0]).GetElementsByTagName("ide");
string tpNF = ((XmlElement)ide[0]).GetElementsByTagName("tpNF")[0].InnerText;
//if (tpNF == "0") continue;
XmlNodeList emit = ((XmlElement)infNFe[0]).GetElementsByTagName("emit");
string emitInfoCod;
if (((XmlElement)emit[0]).GetElementsByTagName("CNPJ").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CNPJ")[0].InnerText;
}
else if (((XmlElement)emit[0]).GetElementsByTagName("CPF").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CPF")[0].InnerText;
}
else
{
emitInfoCod = "0";
}
string ide_dEmi = (((XmlElement)ide[0]).GetElementsByTagName("dEmi").Count > 0)
? ((XmlElement)ide[0]).GetElementsByTagName("dEmi")[0].InnerText
: ((XmlElement)ide[0]).GetElementsByTagName("dhEmi")[0].InnerText;
string[] data = ide_dEmi.Split('-');
string folderName = data[0] + "\\" + data[1];
string organizeStyle = String.Empty;
if (comboBox1.SelectedIndex == 0 || comboBox1.SelectedIndex == 2)
{
organizeStyle = folder + #"\ORGANIZADO\" + emitInfoCod + #"\" + folderName;
}
else
{
organizeStyle = folder + #"\ORGANIZADO\" + folderName + #"\" + emitInfoCod;
}
if (!Directory.Exists(organizeStyle))
{
Directory.CreateDirectory(organizeStyle);
}
folderMove = organizeStyle + "\\";
if (!File.Exists(folderMove + chave + ".xml"))
{
File.Copy(arquivoLoad, folderMove + chave + ".xml");
}
label2.Text = "Arquivos sendo processados, aguarde... (" + i + " / " + arquivos + ")";
label2.Refresh();
i++;
}
label2.Text = "Notas organizadas com sucesso!";
label2.Refresh();
}
public static string ReadFileToString(string filePath)
{
using (StreamReader streamReader = new StreamReader(filePath))
{
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, #"[^\u0000-\u007F]", string.Empty);
}
private void exitBtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
How can I determine what 's going on?
The value of a variable pointing to a reference type is not the object at all, its just the memory address where the object lives.
So when you do the following:
while (true)
{
var myVariable = new MyReferenceType();
}
The only memory you are really reusing is the variable itself (think of a 32 or 64 bit pointer). But on every iteration your are allocating somewhere in memory space enough to fit the new object you've just created and that memory is most definitely not the memory reserved to the previous object.
This is essentially why your memory usage is growing. The "old" objects of previous iterations with no live reference will eventually get collected by the GC, but that could be never if the GC decides that it has enough memory available to avoid it.

Multi attach files from DB row

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());
}

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