I'm using Streamwriter to save my list data to a text file, but the file is always empty when I open it.
I can get the list to display all of the inputs, so the list works. Heres the code for the filewriter.
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile;
string myFileName;
FileInfo myFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
taxpayerFileChooser.ShowDialog();
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose();
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
You can try changing your code like this:
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile = string.Empty;
string myFileName;
FileInfo myFile;
using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
{
taxpayerFileChooser.Filter = "All text files|*.txt";
if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
{
taxpayerFile = taxpayerFileChooser.FileName;
}
}
if (!string.IsNullOrEmpty(taxpayerFile))
{
using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
{
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
}
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
else
{
MessageBox.Show("Data not saved");
}
}
The using statement explicit calls the Dispose() method of disposable objects after the block execution. http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Related
I am trying to decompress a .s file programmatically using c#. I have tried using all the possible methods I know but couldn't decompress it. My actual file would be a file.tar.gz, I have uncompressed .tar.gz using ICSharpCode.SharpZipLib.Tar and ICSharpCode.SharpZipLib.GZip. In my uncompressed folder I would be having different files with "file_1.s" format. Can someone guide me plz?
Here is my function for decompressing:
public void ExtractTGZ(String gzArchiveName, String destFolder)
{
Stream inStream = File.OpenRead(gzArchiveName);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
}
public void ExtractTar(String tarFileName, String destFolder)
{
Stream inStream = File.OpenRead(tarFileName);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
inStream.Close();
}
When a button event Occurs it will select the file.tar.gz from windows explorer and with next button it will start decompressing and its code is as shown below:
private void OpenFileLocationEvent(object sender, EventArgs e)
{
if (openLogs.ShowDialog() == DialogResult.OK)
{
tbTargetFile.Text = openLogs.FileName;
}
}
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
//MessageBox.Show("Source File:" + tbTargetFile.Text + " ExtrctdDirectory:" + nextDirectory);
_uc.ExtractTGZ(tbTargetFile.Text, nextDirectory);//Extract .tar.gz
string[] files = Directory.GetFiles(nextDirectory, "*.s");
string filename = "";
string targetFile = "";
string newFile = "";
int count = 0;
foreach (string f in files)
{//Changing File Type
filename = Path.GetFileName(f);
targetFile = nextDirectory + "//" + filename;
newFile = nextDirectory + "//File_" + count + ".tar";
File.Move(targetFile, newFile);
count += 1;
//FileInfo finfo = new FileInfo(targetFile);
//finfo.MoveTo(Path.ChangeExtension(targetFile, ".txt"));
}
string[] tarfiles = Directory.GetFiles(nextDirectory, "*.tar");
foreach (string f in tarfiles)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
MessageBox.Show("Traget File:" + targetFile + " ExtrctdDirectory:" + extrctdDirectory);
_uc.ExtractTar(targetFile, extrctdDirectory);
//_uc.ExtractTarByEntry(targetFile, extrctdDirectory, false);
//ZipFile.ExtractToDirectory(targetFile, extrctdDirectory);
}
}
}
Using a 7zip console application solved my problem. And this is my code.
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";
p.Arguments = "x \"" + tbTargetFile.Text + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
string[] files = Directory.GetFiles(nextDirectory, "*.tar");
string filename = "";
string targetFile = "";
foreach (string f in files)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
}
p.Arguments = "x \"" + targetFile + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
targetFile = nextDirectory + "\\*.s";
p.Arguments = "x \"" + targetFile + "\" -o\"" + extrctdDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
}
}
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!
I have been trying to organize a code that it is a mess! The first and my biggest problem at this point is that one of my StreamWriters or StreamReader is being left open. Using this link, I am trying to organize my code. But my problem is that I am not sure where should I close it:
My code is:
public static void ProcessFile(string[] ProcessFile, int id_customer, string directoryinprocess)
{
StreamWriter Writer = null, Writer2 = null, Writer3 = null;
foreach (string filename in ProcessFile)
{
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
int rowCount = 0;
string path_body_out = "";
string outputname = folderbefore + "output_temp\\" + fileName;
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
using (StreamReader Reader = new StreamReader(#filename))
{
while (!Reader.EndOfStream)
{
string inputLine = string.Empty;
inputLine = Reader.ReadLine();
rowCount++;
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
}
} // end of the while
} // end of using Stremreader
if (path_body_out.Contains("_hd_intermediate"))
{
ManipulateHeaderFilesTypeRo(dir, path_body_out);
}
else
{ }
} // end of the foreach
string[] extensions = { "_fv", "_body", "_out" };
string[] fileEntriesout = System.IO.Directory.EnumerateFiles(directoryinprocess, "*.csv", System.IO.SearchOption.AllDirectories)
.Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex)))
.ToArray();
foreach (string filenameout in fileEntriesout)
{
string destinytablename = null;
if (filenameout.Contains("_hd_intermediate_fv"))
{ destinytablename = "TBL_DATA_TYPE_RO_HEADER"; }
else if (filenameout.Contains("_body_out"))
{ destinytablename = "TBL_DATA_TYPE_RO_BODY"; }
else
{ destinytablename = "TBL_DATA_TYPE_LOAD"; }
string id_file = Get_id_file(filenameout, id_customer);
DataTable csvFileData = GetDataTabletFromCSVFile(filenameout, id_file);
InsertDataIntoSQLServerUsingSQLBulkCopy(csvFileData, destinytablename);
} // end of the foreach
//} // end of the foreach
} // end of ProcessFile
Question:
How should I close the part:
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
using (StreamReader Reader = new StreamReader(#filename))
{
while (!Reader.EndOfStream)
{
string inputLine = string.Empty;
inputLine = Reader.ReadLine();
rowCount++;
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
Should I close here?
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
Or here?
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
}
If you can't reorganize this code so that every StreamWriter instance can be wrapped in a using(), then perhaps you can do something like this:
StreamWriter Writer = null, Writer2 = null, Writer3 = null;
try
{
// your existing code
}
catch
{
// Handle
}
finally
{
if (Writer != null)
Writer.Close();
if (Writer2 != null)
Writer2.Close();
if (Writer3 != null)
Writer3.Close();
}
This ensures that no matter what error(s) happen within the try that your writers will be closed.
In my opinion, conditionally instantiating objects is a smell and you should work on having different implementations based on filename.Contains("RO_"). You could use the strategy pattern and have different file processor interface implementations, choosing the correct one based on the filename. Each implementation would only know how to write to the locations it needs. This would allow you to correctly use a using() around each writer.
Nomrally if you are using disposable objects, I would say use a using block. However, since you are conditionally instatiating disposable objects, I think the use of a try-finally block would be your best bet.
Declare disposable objects and intialize them to null outside of a try block.
Initialize the disposable objects to the instances you want inside of a try block. Take care not to change this reference anywhere inside of your try-block once you have created a disposable object.
Also inside of your try block, do everything you need to do with the disposable objects.
After your try block create a finally block (a catch block is optional, but you will need a finally block for this method to do its job.) and inside the finally block, check if the variables you declared to hold the disposable objects aren't null. and if they are not null, close them and make them null.
StreamWriter writer = null;
try {
if (condA) {
writer = new StreamWriter("filePath1");
} else if (condB) {
writer = new StreamWriter("filePath2");
} else {
writer = new StreamWriter("filePath3");
}
// do things with writer
} catch (Exception ex) {
} finally {
if (writer != null) {
writer.close();
writer = null;
}
}
So, I am trying to create a file at a specific path but the code I have doesn't allows me to create folders.
This is the code I have:
public void LogFiles()
{
string data = string.Format("LogCarga-{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now);
for (int linhas = 0; linhas < dataGridView1.Rows.Count; linhas++)
{
if (dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim() != "M")
{
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logs\";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (StreamWriter writer = File.AppendText(filePath + data))
{
string carga = dataGridView1.Rows[linhas].Cells[0].Value.ToString();
string referencia = dataGridView1.Rows[linhas].Cells[1].Value.ToString();
string quantidade = dataGridView1.Rows[linhas].Cells[2].Value.ToString();
string dataemissao = dataGridView1.Rows[linhas].Cells[3].Value.ToString();
string linha = dataGridView1.Rows[linhas].Cells[4].Value.ToString();
string marca = dataGridView1.Rows[linhas].Cells[5].Value.ToString().Trim();
string descricaoweb = dataGridView1.Rows[linhas].Cells[6].Value.ToString().Trim();
string codprod = dataGridView1.Rows[linhas].Cells[7].Value.ToString().Trim();
string tipoemb = dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim();
string nomepc = System.Environment.MachineName;
writer.WriteLine(carga + ", " + referencia + ", " + quantidade + ", " + dataemissao + ", " + linha + ", " + marca + ", " + descricaoweb + ", " + codprod + ", "
+ tipoemb + ", " + nomepc);
}
}
}
}
}
This %USERPROFILE%\AppData\Local\ in the universal path and I want to automatically create the \Cargas - Amostras\_logs\.
Do you have any idea how to do it?
The simpelest solution is replace
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
with
System.IO.Directory.CreateDirectory(filePath)
That will create the directory if it does not exist or do nothing if it does.
You need to create two checks, for your first folder and then second directory.
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\";
if (System.IO.Directory.Exists(pathWithEnv))
{
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are found.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are available.
}
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are available now.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are created.
}
}
I know others had a similar problem but my problem is specific for image...
I have an image function like below:
static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform)
{
ofd.Title = "Select Pictures";
ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png | All file (*.*)| *.*";
ofd.DefaultExt = ".jpg"; // Default file extension
string namefile = "";
// Process open file dialog box results
if (ofd.ShowDialog() == DialogResult.OK)
{
// try
//{
string fileName = ofd.FileName;
if (ofd.SafeFileName.Length <= 50)
if (Image.FromFile(fileName).Width >= 640 && Image.FromFile(fileName).Height >= 480)
{
namefile = ofd.SafeFileName;
if (namefile != "Null_0_Null" || namefile != null)
{
string oldPath = #ofd.FileName;
string newFileName = namefile;
newpath = Application.StartupPath + #"\userpictures\" + #"Apartment\";
deladdress = newpath + folderform + #"\" + #newFileName;
Random rand = new Random();
string pp=newpath+folderform;
// string pdest;
#region Check Directory And File To copy
if (Directory.Exists(newpath + folderform))
{
if (!File.Exists(newpath + folderform + #"\" + #newFileName))
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
// else
// {
// File.Delete(newpath + folderform + #"\" + #newFileName);
// File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
//}
}
else
{
Directory.CreateDirectory(newpath + folderform);
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
}
#endregion
pictureBox.BackgroundImage = Image.FromFile(newpath + folderform + #"\" + #newFileName);
}
else { MessageBox.Show("filename" + namefile + "Not valid"); }
}
else { MessageBox.Show("Size of file not valid"); }
else { MessageBox.Show("size of name file not valid"); }
// }
// catch { MessageBox.Show("your file that you selected is not valid please select anyone."); }
}
return namefile;
}
For loading image I have this function:
static public void loadimage(PictureBox pictureBox, string img, string nameform, string folderform)
{
try
{
if (img != "Null_0_Null")
if (!System.IO.File.Exists(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img))
{
pictureBox.BackgroundImage = Image.FromFile(Application.StartupPath + "\\filepictures\\default4.PNG");
}
else
{
pictureBox.BackgroundImage =Image.FromFile(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img);
}
}
catch { }
}
In my form I call this functions. For set image I write a private string in my form:
string img1;
And for loading image in my form load write this:
loadimage(pictureBox1, "Blue hills.jpg","me", "Apartment");
img1 = "Blue hills.jpg";
For Setimage I have this:
img1=Setimage(pictureBox1, openFileDialog1,"me", "Apartment");
And when I use this code for delete image show me error "process can not be access ..."
System.IO.File.Delete("image path");
When you use Image.FromFile, that will open a file handle to that file and keep it open until the image is disposed.
You should:
Only call Image.FromFile once and reuse the object in Setimage (you're loading it twice in a single if condition...)
Dispose of every Image when you're done with it
Dispose of the old BackgroundImage before you set the new one
So long as you dispose of every Image which is related to the file before you delete the file, you should be okay.