Save file to a specific folder in Windows Form C# - c#

I am trying to save some selected file in a folder(images) inside my application
I am able to get the file using following code:
private void button1_Click(object sender, EventArgs e)
{
string imagelocation = "";
OpenFileDialog dialog = new OpenFileDialog();
if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
textBox2.Text = dialog.FileName;
}
}
For saving the file I got in textBox2, I tried following code. But with following code I have to also select the path where I want to save the file.
What If I want to (set my path permanently to 'images' folder as shown in pic) for saving?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
if(f.ShowDialog() == DialogResult.OK)
{
using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
using(StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox2.Text);
}
}
}

2 Approaches to Solve this problem
First Approach: (Browser the File and click Save, to automatically save the selected file to Image Directory)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
using (Stream s = File.Open(imageDir+"\\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
Second Approach: (Browser the File and Save Opens SaveDialog with Directory as Image Directory and File name as Previously selected File)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = imageDir;
f.FileName = textBox1.Text;
if (f.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(imageDir + "\\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}```

Does this code work for you?
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Select Picture";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
}
}

Related

Issue with method CopyTo

I'm working on my first WPF application, and I'm trying to copy the browsed image into designated folder, however I have problem with CopyTo function.
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Select image(*.JPG;*.PNG)|*.JPG;*.PNG";
openFileDialog1.Title = "Select your image";
openFileDialog1.InitialDirectory = #"C:\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// The image to be shown into PictureBox
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
// The Image
var theImg = Image.FromFile(openFileDialog1.FileName);
string fileName = openFileDialog1.FileName;
if(theImg != null)
{
string exePath = System.Environment.GetCommandLineArgs()[0];
string destinationFolder = Path.Combine(exePath, "Profiles");
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
}
string filePath = Path.Combine(destinationFolder, fileName);
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
theImg.CopyTo(theImg, fileStream);
}
}
}
}
Error: No overload for method 'CopyTo' takes 2 arguments
How can I solve this issue? Thank you in advance

How to insert file directory

I made a program with iTextSharp which allows the user to click on a button to choose a file and do the main function with the second button.
Now I want to make a button which will replace this function in the second button:
using (Stream dest = File.Create(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf"))
I want to make a third button which will get the chosen location by the user, not a given location which is not changeable.
The whole Code:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
byte[] bytes = File.ReadAllBytes(theFile);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12,
iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (Stream source = File.OpenRead(theFile))
using (Stream dest = File.Create(theCFile))
{
PdfReader reader = new PdfReader(source);
using (PdfStamper stamper = new PdfStamper(reader, dest))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT,
new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) ;
}
Use the FolderBrowserDialog class to select a folder location.
You can combine the output folder and filename using Path.Combine(selectedFolder, filename) and place that in the using statement.
Code for saving the selected output folder:
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedPath = FD.SelectedPath;
theCFile = Path.Combine(selectedPath, theFile)
}
}

C#, saving from menu strip, and save as button

I am trying to save my rich text box content to a a file. However I am getting the error when I am trying to save a new file. Save as works as expected. Any suggestions. Thank you
System.ArgumentException: 'Empty path name is not legal.'
My code for the save and save as button are as follows:
OpenFileDialog file_open = new OpenFileDialog();
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
filename = file_open.FileName;
RichTextBoxStreamType stream_type;
// Checks the extension of the file to save
if (filename.Contains(".txt"))
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
DialogResult retval = saveDlg.ShowDialog();
if (retval == DialogResult.OK)
filename = saveDlg.FileName;
else
return;
RichTextBoxStreamType stream_type;
if (saveDlg.FilterIndex == 2)
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
MessageBox.Show("File Saved");
}

Copy PDF to other folder with OpenFileDialog C# WPF

I tried complete my program, with this code:
private void btnBuscar_Click(object sender, RoutedEventArgs e)
{
FileInfo f = null;
OpenFileDialog dlg;
dlg = new OpenFileDialog();
dlg.Filter = "Document Files (*.doc;*pdf)|*.doc;*pdf";
dlg.InitialDirectory = Environment.SpecialFolder.UserProfile.ToString();
dlg.Title = "Seleccione su archivo de cotizaciĆ³n.";
//Open the Pop-Up Window to select the file
bool? result = dlg.ShowDialog();
if (result == true)
{
f = new FileInfo(dlg.FileName,);
using (Stream s = dlg.OpenFile())
{
TextReader reader = new StreamReader(s);
string st = reader.ReadToEnd();
txtPath.Text = dlg.FileName;
}
File.Copy(dlg.FileName,#"C:\Formatos\m1");
}
}
The problem is when select the file with OpenFileDialog the program Crash automatically. I need copy the files only, and save the path of the copy file in the DB.
Thank you for you help!
Change bool? result = dlg.ShowDialog(); to if (dlg.ShowDialog() == DialogResult.OK)
Also, remove the extra comma from f = new FileInfo(dlg.FileName,);

The process cannot access the file 'E:\test.txt' because it is being used by another process

I'm trying to remove out-of-sequence white spaces from a text file to one-space sequence in a winForm i.e.,
From
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
To
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
My implementation is:
private void buttonBrowse_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialogImage = new OpenFileDialog();
openFileDialogImage.Filter = "Text files | .txt";
openFileDialogImage.Multiselect = false;
if (openFileDialogImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialogImage.OpenFile()) != null)
{
textBoxFileName.Text = openFileDialogImage.FileName;
}
}
}
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
using (StreamReader reader = new StreamReader(path, true))
{
s = reader.ReadToEnd();
}
string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
File.CreateText(pathSave);
using (StreamWriter sw = new StreamWriter(pathSave))
{
sw.Write(parts);
}
}
}
}
Error that I am getting on line using (StreamWriter sw = new StreamWriter(pathSave)) is:
The process cannot access the file 'E:\test.txt' because it is being used by another process.
I downloaded ProcessWorker to see which process is currently locking Test.txt but I don't see any process using it. Any ideas on how to solve it?
In addition to the other suggestions, your problem is that File.CreateText() will lock so you need to release the lock. I have wrapped the call to File.CreateText() in a using statement to release the lock.
There was an issue with the output of the StreamWriter so I made some changes to get the expected output as per your question.
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
string[] parts;
using (StreamReader reader = new StreamReader(path, true))
{
parts = reader.ReadToEnd().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
using (File.CreateText(pathSave))
{ }
using (StreamWriter sw = new StreamWriter(pathSave))
{
string result = string.Empty;
foreach (string s in parts)
{
result += s + " ";
}
sw.Write(result);
}
}

Categories