C# streamwriter create part of files - c#

I am trying to create a hash text file. The code works, the problem is that once the streamwriter starts the process it won't stop until it is finished. I want to break up the output file into smaller parts. How do I stop the streamwriter and start a new file without starting the process over again?
string infile = #"ntlmchar.txt";
string hashfile = #"ntlmhash.txt"; //File that includes the hash and clear test
string charfile = #"ntlmchar.txt"; //File that only has the clear text
string oldCharFile = ""; //Temp file to apply to infile.
int cint = 1; //The number of characters in the file
string str_cint = cint.ToString(); //convert cint to string
int pint = 1; //The number of parts to the character file
string str_pint = pint.ToString(); //convert pint to string
int cm = 4; //Max number of characters
int pm = 4000; //Man number of parts
int line = 0; //line index number
while (cint <= cm)
{
if (!File.Exists(infile))
{
for (int ci =1; ci <= cm; ci++)
{
str_cint = cint.ToString();
for (int pi =1; pi <= pm; pi++)
{
str_pint = pint.ToString();
// System.Console.WriteLine("Inner for loop cint file does not exist" +cint +" pint " + pint);
// System.Console.WriteLine("Inner for loop str_cint file does not exist " + str_cint + " cint " + cint);
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
pint = pi;
oldCharFile = charfile;
infile = oldCharFile;
if (File.Exists(infile)) break;
// System.Console.WriteLine("inner loop file " + infile);
}
// System.Console.WriteLine("outer for loop cint " + cint + " pint " + pint);
// System.Console.WriteLine("infile not found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
// System.Console.WriteLine("No work files found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
else if (File.Exists(infile))
{
// Create a file to write to.
// System.Console.WriteLine("cint at the start of else if " + cint + " str_cint " + str_cint);
infile = oldCharFile;
str_cint = cint.ToString();
// System.Console.WriteLine("cint after assign to str_cint " + cint + " str_cint " + str_cint);
pint=1;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
//System.Console.WriteLine(infile + " " + oldCharFile + " " + charfile + " " + hashfile);
// System.Console.WriteLine("Infile found " + cint + " " + pint);
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
foreach (string s in alpha)
{
if (line <= 2000000)
{
string j = i + s;
string str = Program.Ntlm(j);
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
// System.Console.WriteLine("line before writing to file " + line + " in charfile " + charfile);
h.WriteLine("{0}, {1}", j, str);
c.WriteLine("{0}", j);
line++;
// System.Console.WriteLine("h file" + h + " c file" + c);
}
else
{
h.Flush();
c.Flush();
pint++;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
line = 1;
System.Console.WriteLine("line after writing to part of file " + line + " in charfile " + charfile);
}
}
}

I assume you're trying to get 2,000,000 items per file? You just need to restructure a little.
Right now you have:
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
You need to change your code so that you open the output files later:
using (StreamReader sr = new StreamReader(infile))
{
StreamWriter h = null;
StreamWriter c = null;
try
{
h = new StreamWriter(...);
c = new StreamWriter(...);
string i = "";
while ((i = sr.ReadLine()) != null)
{
// output line here
// and increment line counter.
++line;
if (line > 2000000)
{
// Close the output files and open new ones
h.Close();
c.Close();
h = new StreamWriter(...);
c = new StreamWriter(...);
line = 1;
}
}
}
finally
{
if (h != null) h.Close();
if (c != null) c.Close();
}
}

Related

Results in descending order

I've got a block of code which sums up time togged for various tasks in a project and returns the total hours logged per project (intMinutesLogged). How do I get my results n descending order?
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> dicEntriesByWorkspace, string strChatURL)
{
string strMessage = "";
foreach (var kvpEntry in dicEntriesByWorkspace)
{
var lstTimeEntries = kvpEntry.Value;
string strTitle = "";
var intMinutesLogged = 0;
var intMinutesBillable = 0;
var intMinutesNonBillable = 0;
foreach (var objTimeEntry in lstTimeEntries)
{
if (objTimeEntry.Billable)
{
intMinutesBillable += objTimeEntry.TimeInMinutes;
}
else
{
intMinutesNonBillable += objTimeEntry.TimeInMinutes;
}
}
strTitle = Workspaces.getWorkspaceFromCache(kvpEntry.Key).Title;
//Console.WriteLine(intMinutesLogged + ": " + strTitle + "m");
intMinutesLogged = intMinutesBillable + intMinutesNonBillable;
Console.WriteLine(TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")");
strMessage += TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")" + "\n";
}
await SendMessage(strChatURL, strMessage);
}
static string TimeLoggedMessage(int intMinutesLogged)
{
return intMinutesLogged / 60 + "h" + " " + intMinutesLogged % 60 + "m";
}
You could use LINQ for this: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending?view=net-6.0
You could create a simple class or anonymous type to hold the integer values you're summing up (total minutes, billable minutes, non-billable minutes). Then you could populate a collection of this type within the code you shared and afterwards call OrderByDescending on it. You could order based on any of the three integer values.

Encoding missing from reading file

Hello i'm developing a little application that download attachment from unread mails by imap and make a sevarla job on this attachment. Problem is encoding because after i have saved a, for example, txt file, when i load it again letters with accents becomes "?" I dont know why. I tried a several example around on the web (like converting directly the file from ansi to utf-8) with no result. Whe i open a file in windows it works, words are correct.
i have used either ReadAllText that StreamReader in the following example:
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
as you can see in the following example if i set directly a string with an accent word, it works, from file no.
Please help me!
check image
Reproducible Code:
using CsvHelper;
using NLog;
using System;
using System.Data;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void test2()
{
using (var client = new ImapClient())
{
try
{
int porta = Convert.ToInt32(par.portaimap);
bool ssl = Convert.ToBoolean(par.sslimap);
client.Connect(par.host, porta, ssl);
Logger.Info("Connessione server posta riuscita");
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
try
{
Logger.Info("Autenticazione in corso");
client.Authenticate(par.usernameimap, par.passwordimap);
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
var query = SearchQuery.NotSeen;//SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit"));
var uids = client.Inbox.Search(query);
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
Logger.Info("Selezione lista di email non lette");
foreach (var summary in items)
{
var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\", summary.UniqueId.ToString());
// create the directory
Directory.CreateDirectory(directory);
if (summary.Body is BodyPartMultipart)
Logger.Info("Download allegati in corso.");
foreach (var attachment in summary.Attachments)
{
var entity = client.Inbox.GetBodyPart(summary.UniqueId, attachment);
var part = (MimePart)entity;
// note: it's possible for this to be null, but most will specify a filename
var fileName = part.FileName;
var path = Path.Combine(directory, fileName);
try
{
using (var stream = File.Create(path))
part.Content.DecodeTo(stream);
Logger.Info("Allegato scaricato.");
}
catch (Exception ex)
{
Logger.Error("Allegato non scaricato. Di seguito errore: " + ex.Message);
}
int scelta = 0;
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
Console.WriteLine(contents);
Console.ReadLine();
contents = "Proprietà";
Console.WriteLine(contents);
Console.ReadLine();
string ext = Path.GetExtension(fileName);
SmtpSettings smtpSettings = new SmtpSettings();
smtpSettings.SenderName = "Test";
smtpSettings.server = "smtp.gmail.com";
smtpSettings.Port = 587;
smtpSettings.SenderMail = par.usernameimap;
smtpSettings.Username = par.usernameimap;
smtpSettings.Password = par.passwordimap;
smtpSettings.ToMail1Name = "Test1";
smtpSettings.ToMail1 = "test1#gmail.com";
smtpSettings.ToMail2Name = "Test2";
smtpSettings.ToMail2 = "Test2#bsolution.org";
string PATHTODELETE = "";
if (ext == ".txt")
{
string line1 = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName).First();
if (line1 == "FOR|CLIEN|STAB|INSEGNA|INDIRIZZO|CAP|LUOGO|PROV|ORDINE|POS|STATO|DTORD|ORAORD|MALFUNZIONE|COD_RIS|RISORSA|TERMID|ESESIA|STABSIA|ABI|TELEFONO|NOTE|COD_HOST|ACCESSORIO|DESC_HOST|MOD_COLLEG|FUNZ. AGG:|REFERENTE|DT_SCADENZA|LAKA|")
{
DataTable dt;
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = "|";
// Do any configuration to `CsvReader` before creating CsvDataReader.
using (var dr = new CsvDataReader(csv))
{
dt = new DataTable();
dt.Load(dr);
reader.Close();
}
}
//Costruzione body mail csv
string value = "";
string filename = "";
string Msg = "";
foreach (DataRow drow in dt.Rows)
{
value = "";
value += "FOR: " + drow["FOR"].ToString() + "\n";
value += "CLIEN: " + drow["CLIEN"].ToString() + "\n";
value += "STAB: " + drow["STAB"].ToString() + "\n";
value += "INSEGNA: " + drow["INSEGNA"].ToString() + "\n";
value += "INDIRIZZO: " + drow["INDIRIZZO"].ToString() + "\n";
value += "LUOGO: " + drow["LUOGO"].ToString() + "\n";
value += "ORDINE: " + drow["ORDINE"].ToString() + "\n";
value += "POS: " + drow["POS"].ToString() + "\n";
value += "STATO: " + drow["STATO"].ToString() + "\n";
value += "DTORD: " + drow["DTORD"].ToString() + "\n";
value += "ORAORD: " + drow["ORAORD"].ToString() + "\n";
value += "MALFUNZIONE: " + drow["MALFUNZIONE"].ToString() + "\n";
value += "COD_RIS: " + drow["COD_RIS"].ToString() + "\n";
value += "RISORSA: " + drow["RISORSA"].ToString() + "\n";
value += "TERMID: " + drow["TERMID"].ToString() + "\n";
value += "ESESIA: " + drow["ESESIA"].ToString() + "\n";
value += "STABSIA: " + drow["STABSIA"].ToString() + "\n";
value += "ABI: " + drow["ABI"].ToString() + "\n";
value += "TELEFONO: " + drow["TELEFONO"].ToString() + "\n";
value += "NOTE: " + drow["NOTE"].ToString() + "\n";
value += "COD_HOST: " + drow["COD_HOST"].ToString() + "\n";
value += "ACCESSORIO: " + drow["ACCESSORIO"].ToString() + "\n";
value += "DESC_HOST: " + drow["DESC_HOST"].ToString() + "\n";
value += "MOD_COLLEG: " + drow["MOD_COLLEG"].ToString() + "\n";
value += "FUNZ. AGG: " + drow["FUNZ. AGG:"].ToString() + "\n";
value += "REFERENTE: " + drow["REFERENTE"].ToString() + "\n";
value += "DT_SCADENZA: " + drow["DT_SCADENZA"].ToString() + "\n";
value += "LAKA: " + drow["LAKA"].ToString();
Msg = value;
// Save File to .txt
filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
using (FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg, Encoding.UTF8);
m_WriterParameter.Flush();
m_WriterParameter.Close();
}
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
Invio(smtpSettings, Msg, filename);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
Logger.Info("Pulizia directory allegati terminata.");
}
else
{
string[] stringSeparators = new string[] { "************************************************************************************************************" };
string[] attivita = contents.Split(stringSeparators, StringSplitOptions.None);
foreach (string att in attivita)
{
Console.WriteLine(att);
string Msg = att;
// Save File to .txt
string filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write);
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg);
m_WriterParameter.Flush();
m_WriterParameter.Close();
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
if (att.Contains("OGGETTO"))
{
Invio(smtpSettings, att, filename);
}
else { }
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
Logger.Info("Pulizia directory allegati terminata.");
}
}
else
{
}
}
}
}
}
}
}
After searching around on the web i found a solution, here microsoft msdn
Streamreader and maybe readalltext doesn't support accent letters with UTF-8 Encoding, so changing it in UTF-7, letters are showed correctly.
Thank you for all support!

How to retrieve data from text file

I have data appended line by line in a text file for all confirmed transaction. I want to add Search functionality, where the user enters their E-mail address and all related transaction details connected to that E-mail must be displayed.
bool writeNextLine = false;
StringBuilder sb = new StringBuilder();
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader("record.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(txt_SearchBooking.Text))
{
// This append the text and a newline into the StringBuilder buffer
sb.AppendLine(line.ToString());
lbl_result.Text += sb.ToString();
}
}
}
but only the line containing Email is displayed other details are not.
Email is located on the last line of every transaction detail.
confirmmsg =
" Transaction # : " + EmployeeIDTextBox.Text + ClientIDTextBox.Text + UniqueIDTextBox.Text + "\r\n"
+ " First Name : " + ClientFirstNameTextBox.Text + "\r\n"
+ " Telephone Number : " + ClientTelephoneNumberTextBox.Text + "\r\n"
+ " Investment : " + investmentamt.ToString("C2") + "\r\n"
+ " Interest : " + (twelvemonthint * 100).ToString() + "%" + "\r\n"
+ " Interest Amount : " + (invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint) - investmentamt).ToString("C2") + "\r\n"
+ " Bonus : " + bonus.ToString("c2") + "\r\n"
+ " Total Returns : " + invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint).ToString("C2") + "\r\n"
+ " E-mail : " + ClientEmailTextBox.Text;
This is the data which is written into the text file.
If you always have 9 lines per transaction, with email being the last line, you could use File.ReadAllLines and a counter.
var lines = File.ReadAllLines("records.txt");
for(int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if(line.Contains(txt_SearchBooking.Text))
{
//Retrieve the previous lines
for(int y = i-8; y <= i; y++)
{
lbl_result.Text += lines[y];
}
}
}

Ho to set timeout for dataset in C#

when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}

prepend headers to my csv file

I want to prepend headers to my CSV File as to let the data reflect the headings. How would I go about this without having to add it each time writing to the file? Meaning I only want the headers added once on each export. When am exporting to the same file name it should not create duplicates of the same headers. Here is my code below which writes to file:
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
MessageBox.Show("Please wait while " +comboBox5.Text+ " table is being exported..");
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
}
System.IO.File.WriteAllText("C:\\Users\\jdavis\\Desktop\\"+comboBox5.Text+".csv", textBox8.Text);
MessageBox.Show("Export of " +comboBox5.Text+ " table is complete!");
textBox8.Clear();
}
Updated attempt:
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported..");
if (!File.Exists(comboBox5.Text))
{
string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
+ "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM" + Environment.NewLine;
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
}
System.IO.File.WriteAllText("C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv", textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
}
I really want to try and achieve it without SteamWriter, where am I going wrong?
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
string path = "C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv";
string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
+ "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM";
MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported..");
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
if (!File.Exists(path))
{
System.IO.File.WriteAllText(path, rxHeader);
System.IO.File.WriteAllText(path, textBox8.Text);
}
else
{
System.IO.File.AppendAllText(path, textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
}
}
Here is the short version that will even properly handle values that contain , and ":
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.RowHeadersVisible = false; // the row headers column is copied too if visible
dataGridView1.SelectAll(); // only the selected cells are used (the Windows Clipboard is not used)
DataObject dataObject = dataGridView1.GetClipboardContent(); // 4 Data Formats: Text,Csv,HTML Format,UnicodeText
File.WriteAllText("1.csv", dataObject.GetData("Csv") as string); // DataFormats.CommaSeparatedValue = "Csv"
//string html = Encoding.ASCII.GetString((dataObject.GetData("HTML Format") as MemoryStream).ToArray()); // just the HTML Clipboard Format is in a MemoryStream
This is my suggested solution.
My suggestion is to first check if the file exists or not, to then decide if you need to write the header or not.
private void DoTheWork(int fileIDtoUpdate)
{
//this is just my representation of what probably already exist in your project
string textInTheTextBox = "blah blah blah blah\nI love text\nI love code\nI love to Code\ndon't you just love to code!";
string filePath1 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File1.txt";
string filePath2 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File2.txt";
string filePath3 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File3.txt";
string filePath4 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File4.txt";
string fileToWorkWith = string.Empty;
//decide which file to work with
switch (fileIDtoUpdate)
{
case 1:
fileToWorkWith = filePath1;
break;
case 2:
fileToWorkWith = filePath2;
break;
case 3:
fileToWorkWith = filePath3;
break;
case 4:
fileToWorkWith = filePath4;
break;
default:
break;
}
//check if the file existed
bool fileExisted = File.Exists(fileToWorkWith);
using (StreamWriter sw = new StreamWriter(fileToWorkWith, true))
{
if (!fileExisted)
{
//if the file did not exist, then you need to put your header line!
sw.WriteLine("Write your Header Line here");
}
sw.WriteLine(textInTheTextBox);//down here... who cares if the file existed or not, you need to append this text to it no matter what!
}
}
Got the answer by simply editing my code with this snippet:
if (!File.Exists(path))
{
System.IO.File.WriteAllText(path, rxHeader + textBox8.Text);
}
else
{
System.IO.File.AppendAllText(path, textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
textBox8.Text = textBox8.Text + "\r\n";
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
}
Just go to the property pannel of textBox8. Text and add column header with comma and set the textbox8 visibility to hidden.

Categories