C# visual studio user input for file path and file name - c#

I have the current code below to save a .csv file on the button click event. However, I want the user to be able to choose the file path and document name. Any suggestions on how to go about that? I could read the text from a text box for a file name, but what about the file path with out the user having to type of it in?
long[][] finalResultArray = dataList.Select(a => a.ToArray()).ToArray();
string filePath = #"C:\test\test.csv";
int length = finalResultArray.GetLength(0);
StringBuilder sb = new StringBuilder();
for(int index = 0; index < length; index++)
{
sb.AppendLine(string.Join(",", finalResultArray[index]));
}
File.WriteAllText(filePath, sb.ToString());
MessageBox.Show("Save Complete!");

You could use the SaveFileDialog class for this:
SaveFileDialog saveFileDialog = new SaveFileDialog();
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, sb.ToString());
MessageBox.Show("Save Complete!");
}

If you want you can also try OpenFileDialog.
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.ShowDialog();

Related

C# Save Image files using SaveFileDialog or FolderBrowserDialog

I'm trying to save image files which are converted from PDF to PNG. I want my application to save the converted image if the PDF was a single page document using the "SaveFileDialog", and if the PDF file was a multi-page document, I then want my application to save them into a folder using the "FolderBrowserDialog".
My problem is that if the PDF file was a multi-page document, my code would first save the first image (after conversion) using the "SaveFileDialog" before attempting to save the rest of the images using "FolderBrowserDialog".
Here is what I've tried.
Image = imageToConvert = null;
for (int i = 0; i < images.Length; i++)
{
if (i == 0)
{
//Save converted image if PDF is single page
imageToConvert = images[i];
SaveFileDialog _saveFile = new SaveFileDialog();
_saveFile.Title = "Save file";
_saveFile.Filter = "PNG|*.png";
_saveFile.FileName = Lbl_OriginalFileName.Text;
if (_saveFile.ShowDialog() == DialogResult.OK)
{
imageToConvert.Save(_saveFile.FileName, ImageFormat.Png);
imageToConvert.Dispose();
}
else if (_saveFile.ShowDialog() == DialogResult.Cancel)
{
return;
}
}
else
{
if (i > 0)
{
// Save converted Images if PDF is multi-page
Image imageToConvert2 = images[i];
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
fbd.Description = "Select the folder you want save your files into.";
string pathString = Path.Combine(fbd.SelectedPath, subFolder);
Directory.CreateDirectory(pathString);
if (fbd.ShowDialog() == DialogResult.Cancel)
{
return;
}
string saveFileNamesPNG = string.Format(Lbl_OriginalFileName.Text + "_" + i.ToString() + ".png", ImageFormat.Png);
imageToConvert.Save(Path.Combine(pathString, saveFileNamesPNG));
imageToConvert.Dispose();
}
}
}
I would really appreciate any help.
I moved the test outside the loop and then checked if it is one page and use the SaveFileDialog. And if there are more than one, I then used a FolderBrowserDialog with the For-loop to save the images.

How to output a .exe file using a program(which in itself is an exe file) in C#?

So this must be easy but quite difficult to search online. All the results give me the answer to how to make an exe file out of a C# program.
Motive:- To make an exe file which runs a random episode of any TV series.
I have made a new WPF application in C# through Visual Studio which asks the user to select a folder, and then runs a random video from all the files in that folder and its sub-folders. But I do not want the user to always go and select the folder. What should I include in the code, for it to save an exe file somewhere with the directory selected by the user. And then the user can conveniently run that file itself.
Here is my code:
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string files="a"; //Initialize
if (result == System.Windows.Forms.DialogResult.OK)
{
//If user presses OK then, 'files' variable is the directory selected
files = fbd.SelectedPath;
}
else if(result == System.Windows.Forms.DialogResult.Cancel)
{
Close();
}
//All Important Video Formats Included to search for
string[] formats = { "mp4", "avi", "mkv", "flv", "wmv", "3gp" };
string[] Allfiles = new string[0];
for (int i=0; i<formats.Length;i++)
{
string[] temp = Directory.GetFiles(files, "*" + formats[i], SearchOption.AllDirectories);
Allfiles = AddArray(Allfiles, temp);
}
//Starts a random Episode
Random episode = new Random();
int Episode = episode.Next(0, Allfiles.Length);
Process.Start(Allfiles[Episode]);
You can write it into a text file and then read it in the other application
Add using System.IO;
Write to a text file:
// Write the string to a file.
StreamWriter file = new System.IO.StreamWriter(txt path);
file.WriteLine(lines);
file.Close();
Read from a text file:
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//close the file
sr.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
If you want to close the app just type this.Close()

Replace SaveFileDialog to saving in code

I have such code that saves bin file, but user has to choose file
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Binary File (*.bin)|*.bin";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
Question.PersistObject(questions, myStream);
myStream.Close();
}
}
But I want to choose file in code, and if a file with such name doesn't exist, then create it. How to set in myStream that file?
Replace all your logic related to the OpenFileDialog with File.Open:
using (var myStream = File.Open(someFilePath, FileMode.OpenOrCreate))
{
Question.PersistObject(questions, myStream); // do something with the stream
}
The OpenOrCreate file mode will open the file if it exists, or create it if it does not.
The using statement will take care of closing the stream for you.
One option would be to have a base name and append a number:
string templateName = "myfile{0}.bin";
string finalName;
int count = 0;
do {
finalName = String.Format(templateName, count++);
} while (File.Exists(finalName);
Or, if you don't care about the name, use Path.GetTempFileName
Then pass that name to StreamWriter:
using (StreamWriter writer = new StreamWriter(finalName))
{
// Write stuff
}

How to save the file using save file dialog box

I want to save any type of file using save file dialog box...
My requirement is based upon the selection of list box(it contain various type of file like .txt,.xls) i want to provide download option using save file dialog box...if user got select .txt file the file store in text format based on the file extension i want to store file...Those file i want to save same to same file copy into the particular location
pl z help me
Dim digresult As DialogResult = MessageBox.Show("Do you want to download ? ", "View", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If digresult = Windows.Forms.DialogResult.Yes Then
downlddialog.Filter = "All files (*.*)|*.*"
downlddialog.Title = "Save a file"
downlddialog.RestoreDirectory = True
downlddialog.OverwritePrompt = True
downlddialog.ShowDialog()
Dim dr As String = downlddialog.FileName
You can pull out the file extension and then appropriate file writing logic for particular file extension see sample code below,
SaveFileDialog oSaveFileDialog = new SaveFileDialog();
oSaveFileDialog.Filter = "All files (*.*) | *.*";
if (oSaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileName = oSaveFileDialog.FileName;
string extesion = Path.GetExtension(fileName);
switch (extesion)
{
case ".txt"://do something here
break;
case ".xls"://do something here
break;
default://do something here
break;
}
}
System.Windows.Forms.SaveFileDialog saveFileDialog1;
saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
DialogResult dr= saveFileDialog1.ShowDialog();
if (dr==DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
//save file using stream.
}
you can use this code this code is in C# instead of MessageBox.Show use System.Windows.Forms.SaveFileDialog
This will do the job...
the filter property is optional - it just if you want the user save a specific file type
VB:
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog ^ saveFileDialog1 = new SaveFileDialog();
saveFileDialog1->Filter =
"JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1->Title = "Save an Image File";
saveFileDialog1->ShowDialog();
// If the file name is not an empty string, open it for saving.
if(saveFileDialog1->FileName != "")
{
// Saves the Image through a FileStream created by
// the OpenFile method.
System::IO::FileStream ^ fs =
safe_cast<System::IO::FileStream*>(
saveFileDialog1->OpenFile());
// Saves the Image in the appropriate ImageFormat based on
// the file type selected in the dialog box.
// Note that the FilterIndex property is one based.
switch(saveFileDialog1->FilterIndex)
{
case 1 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Jpeg);
break;
case 2 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Bmp);
break;
case 3 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Gif);
break;
}
fs->Close();
}
C#
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if(saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch(saveFileDialog1.FilterIndex)
{
case 1 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
fs.Close();
}

save a chart together a txt file with savedialog

I have a listbox, I save it to a txt file with following code.
String[] array = new String[listBox2.Items.Count];
listBox2.Items.CopyTo(array, 0);
Microsoft.Win32.SaveFileDialog saveFileDialog1 = new Microsoft.Win32.SaveFileDialog();
saveFileDialog1.FileName = "per_" ;
saveFileDialog1.DefaultExt = ".txt";
saveFileDialog1.Filter = "Text files (.txt)|*.txt";
Nullable<bool> res = saveFileDialog1.ShowDialog();
if (res == true)
{
string filename = saveFileDialog1.FileName;
File.WriteAllLines(filename, array, Encoding.UTF8);
MessageBox.Show("File saved successfully");
}
I save chart to c://
chart2.SaveImage("C://", System.Drawing.Imaging.ImageFormat.Jpeg);
However I want to save my chart at same direction which user chosed with savefiledialog. What should I do to manage this?
Try this
chart2.SaveImage(Path.GetDirectoryName(saveFileDialog1.FileName), System.Drawing.Imaging.ImageFormat.Jpeg);
or this
chart2.SaveImage(Path.GetDirectoryName(saveFileDialog1.FileName) + "\\chart.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
if SaveImage method needs a filename

Categories