Writing to text files using SaveFileDialog - c#

I'm working on an Add In for Microsoft Excel in Visual Studio that records the balances for each account (or Worksheet) and saves them to a user-specified file. The ability to press a button and select a destination to save your work is an essential skill for any programmer, so I'm perplexed as to why there is so little information on how to do it. The closest thing I found was a tutorial on MSDN that saves a button icon image.
The code I'm currently using is as follows:
StringBuilder sb = new StringBuilder();
if (ThisAddIn.createdbudget)
{
string budget = "Budget = " + ThisAddIn.blake.budget;
SaveFileDialog savebudget = new SaveFileDialog();
savebudget.Filter = "Data files (*.dat)|*.dat|All files (*.*)|*.*";
savebudget.Title = "Save Budget";
savebudget.ShowDialog();
if (savebudget.FileName != "")
{
using (StreamWriter sr = new StreamWriter(savebudget.OpenFile()))
{
sb.AppendLine(budget);
}
}
}
else
{
MessageBox.Show("Control disabled. Budget does not yet exist.");
}
My objective is to allow the user to designate a file path via SaveFileDialog and save a new .dat (or .txt). The stream writer would record the account names and their respective balances line by line. Something like:
sr.WriteLine(Account1.Name + " Balance = " + Account1.Balance);
sr.WriteLine(Account2.Name + " Balance = " + Account2.Balance);
etc...
I know this sounds complicated. I have no problem saving data if I'm using a predetermined file path, but that's not very helpful. What I need to know is how to properly write files using SaveFileDialog.

Related

C#: Saving iText7 PDFs into a folder chosen by the user with a dialog

I would make a simple program in C# with Windows forms, which gets some data given by the user thanks to some textboxes, and when He presses a button, a dialog (I don't know which one) is displayed, in order to explore the pc folders and choose a destination for saving it there.
Well, I used a FolderBrowserDialog (I don't know if that's the right one for the purpose), but there's a problem: in order to store a PDF with itext7, I have to give an Environment.SpecialFolder variable, while the method selectedPath() to get the user path of the formBrowserDialog returns a string.
I tried to convert the string into Environment.SpecialFolder in some way, but I always get a System.ArgumentException
Here's my code:
string name = txtName.Text;
//
//bla bla bla getting the parameters given by the user
//...
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
string folder="";
//"fbd" is the FolderBrowserDialog
if (fbd.ShowDialog() == DialogResult.OK)
{
//here I get the folder path (I hope I've chosen the right dialog for this scope, which is a FolderBrowserDialog)
folder = fbd.SelectedPath;
//starting my pdf generation
//here is my attempt to write something in order to parse the path string into an Environment.SpecialFolder type, to use it as a parameter in getFolderPath()
Environment.SpecialFolder path = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), folder);
//here it's supposed to give to the GetFolderPath method the Environment.SpecialFolder type.
var exportFolder = Environment.GetFolderPath(path); //ON THIS LINE I GET THE EXCEPTION
var exportFile = System.IO.Path.Combine(exportFolder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("
//bla bla bla writing my things on it
"));
}
}
//pdf creation ends
}
To simplify all of this, you don't need to Environment.SpecialFolder variable at all, nor do you need to pass it as a parameter.
The reason that an exception was thrown is because you tried to parse a string into an Environment.SpecialFolder variable enum, when the string could not be parsed into one.
You can look here to see the list of enums included. I would wager that the specific path you selected matches none of those.
Here's what your code is currently doing:
Selecting a path
Trying to parse that path to get an enum for a
special folder
Trying to get the string associated with that
Environment.SpecialFolder variable (so if you had actually been
able to parse it, you would've ended up with just what you started
with)
Combining that string with the name you wanted to give the PDF.
You can simplify all of this by omitting steps 2 and 3, which cause the error.
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
//You select the folder here
if (fbd.ShowDialog() == DialogResult.OK)
{
string folder = fbd.SelectedPath;
//combine the path of the folder with the pdf name
string exportFile = System.IO.Path.Combine(folder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("//bla bla bla writing my things on it"));
}
}
//Pdf creation ends
}

How do you save and preview an HTML file from temp folder?

I'm developing an HTML editor in C# where you can edit your code in the FastColoredTextBox.dll component. You will have this option in the MenuStrip called "Preview in browser" and there will be a drop down item called "Chrome" and "Iexplore" etc. I want it instead of saving the file, i want it to make a file in the Temp folder and preview it. and after we've modified the code again, the file will update as we preview it again. This is what i have so far:
string location = null;
string sourcecode = FastColoredTextBox1.Text;
location = System.IO.Path.GetTempPath() + "\\TempSite.html";
using (StreamWriter writer = new StreamWriter(location, true))
{
writer.Write(sourcecode);
writer.Dispose();
}
try
{
System.Diagnostics.Process.Start("chrome.exe", location);
}
catch (Exception ex)
{
Interaction.MsgBox(ex.Message);
}
How do you achieve this?
Q: How do you save and preview an HTML file from temp folder?
A: You're already doing precisely that :)
Q: Why does my browser keep re-displaying the original image?
A: Because your browser is reading the html from cache.
SOLUTION:
Give your new file a different name. For example:
location = System.IO.Path.GetTempPath() + Path.GetTempFileName() + ".html";
... OR ...
location = Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
You can also simply hit <F5> to refresh, <Ctl-Shift-Del> to clear cache, or disable cache in your browser.

How to make 2 process access the same path?

I'm using c#. I'm receiving an error about a path is currently accessed by other processes. What my system is trying to do is to access the path: #"C:\temps\" + client_ids + "_" + rown + ".pdf" and use the same path for attachment before sending it to client's email.
here's what I've done so far. I comment out some of my code because I'm not sure what to do.
FileStream fs = null;
using (fs = new FileStream(#"C:\\temps\\" + client_ids + "_" +
rown + ".pdf",
FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
TextReader tr = new StreamReader(fs);
//report.ExportToDisk
//(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat,tr);
//report.Dispose();
//Attachment files = new Attachment(tr);
//Mailmsg.Attachments.Add(files);
//Clients.Send(Mailmsg);
}
you can make temp copy of file before you use it in mail attachment and then use the copy instead of the original file
You cannot attach a file to an email if that file is open. You must close (save) the file first.
While #ali answer is technically correct, it is unnecessary. Why go through the overhead of creating a copy of the file which then needs to be deleted, etc.?
Assuming I understand what you are trying to do correctly, simply move your code for mail to after the file is successfully created and saved. And, I don't think you need the overhead of either the filestream or the textreader. As long as your report object can save the file to disk someplace, you can attach that file to your email message and then send it.
While I do not claim to know anything about how Crystal Decisions handles exports, etc. Perhaps something like this would work:
(I got this code from: https://msdn.microsoft.com/en-us/library/ms226036(v=vs.90).aspx)
private void ExportToDisk (string fileName)
{
ExportOptions exportOpts = new ExportOptions();
DiskFileDestinationOptions diskOpts =
ExportOptions.CreateDiskFileDestinationOptions();
exportOpts.ExportFormatType = ExportFormatType.RichText;
exportOpts.ExportDestinationType =
ExportDestinationType.DiskFile;
diskOpts.DiskFileName = fileName;
exportOpts.ExportDestinationOptions = diskOpts;
Report.Export(exportOpts);
}
You will need to change the ExportFormatType property.
Then, simply attach the file to your email and send:
Attachment Files = new Attachment(filename);
Mailmsg.Attachments.add(files);
Clients.Send(Mailmsg);

How to Print logo with bill receipt?

I'm working Windows Application and C#, my application based on restaurant billing process. when i generate the bill its print with logo.
Now, its only print text format.
We are using our application its write all text information through stream writer from notepad file.
This is my sample code,
string strTextFileName = "ESC" + "1" + ".txt";
string strTextFilePath = Application.StartupPath + "\\" + strTextFileName;
if (File.Exists(strTextFilePath))
File.Delete(strTextFilePath);
using (StreamWriter sw = new StreamWriter(strTextFilePath))
{
sw.WriteLine("---------------------");
sw.WriteLine("start s for testing of the Print in t end");
}
Please anyone help to me.

saveFileDialog create new folder and save inside it

i wanna create backup data in my application I used saveFileDialog, so i can place backup file anywhere i want (Dekstop, drive D, etc)
my backup file will be db, image, video so i guess it's will be easier to place that in one folder let say it's "myBackup" folder (generate automatically with C#)
so if user wanna save in Dekstop all of backup data will be in ~C:\Users\Maju\Desktop\myBackup~
i already successfully generate folder but my file won't save inside that
mySaveFileDialog.FileName = "Backup Database " + dateTimeNow;
if (mySaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileAsal = System.IO.Path.Combine(Global.myDatabaseLocation, "data.mdb");
FileInfo fi = new FileInfo(mySaveFileDialog.FileName);
string nameFolder = "myBackup";
System.IO.Directory.CreateDirectory(#fi.DirectoryName + "\\" + nameFolder);
string path = System.IO.Path.Combine (fi.DirectoryName, "\\" + nameFolder);
string pathDestination = System.IO.Path.Combine(path, mySaveFileDialog.FileName);
System.IO.File.Copy(fileAsal, pathDestination, true);
}
Is not it easier to use FolderBrowserDialog?
mySaveFileDialog.FileName already includes the path to the file so you need to write
string pathDestination = System.IO.Path.Combine(path, System.IO.Path.GetFileName(mySaveFileDialog.FileName));

Categories

Resources