I am trying to output the file address of an item selected in a combobox. But i keep getting the Directory address of the project and not the item itself. Please help. Here is my Code:
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (availableSoftDropBox.SelectedItem.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
txtFlashFile.Text = openFileDialog1.FileName;
}
else
{
string fileName;
fileName = Path.GetFullPath((string)availableSoftDropBox.SelectedItem);
string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\" + (fileName);
txtFlashFile.Text = fullPath;
I'm not quite sure what you want to achieve, but using FileInfo instead of Path.GetFullPath might help.
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
const string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\";
string selection = (string)availableSoftDropBox.SelectedItem;
var fileInfo = new FileInfo(fullPath + selection);
string text = fileInfo.FullName;
if (selection.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
text = openFileDialog1.FileName;
}
}
txtFlashFile.Text = text;
}
Related
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
I have a listbox which i can fill trough openfiledialog, which works but not the way i want it. I need 2 columns in my listbox 1 for the filepath and 1 for the fileName next to each other.
also i have another button which inserts all fileNames into the database, which works also but i also need the second column to update the path column in my database
Ive tried to make 2 columns 1 for the filename and 1 for the filepath, unfortunately i could only make 1 column work for my filename.
This is the code for filling in the listbox
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(System.IO.Path.GetFileName(filename));
}
}
this is the code for inserting into the database
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (String string2 in lbfiles.Items.Cast<String>().ToList())
{
{
string cat1 = string2.Substring(0, string2.Length);
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
String query = "INSERT INTO tblBestanden2 (BestandNaam,toegewezen,Username,Status) VALUES (#BestandNaam, #toegewezen, #username, #Status)";
using (SqlCommand command = new SqlCommand(query, sqlCon))
{
command.Parameters.AddWithValue("#BestandNaam", cat1);
command.Parameters.AddWithValue("#toegewezen", "1");
command.Parameters.AddWithValue("#username", "");
command.Parameters.AddWithValue("#Status", "0");
sqlCon.Open();
int result = command.ExecuteNonQuery();
if (!dupe)
{
if (result == 0)
{
sqlCon.Close();
MessageBox.Show("error");
}
else
{
sqlCon.Close();
MessageBox.Show("toegevoegd");
}
dupe = true;
}
}
}
}
}
}
If there is any confusion about my question please tell me and i will try my best to elaborate
Create a class with two properties:
public class File
{
public string Name { get; set; }
public string Path { get; set; }
}
And instances of this one to the ListBox:
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(new File() { Name = System.IO.Path.GetFileName(filename), Path = filename });
}
}
You would then get the values by casting the items to File objects in your BtnToDatabase_Click event handler:
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (File file in lbfiles.Items.OfType<File>())
{
string name = file.Name;
string path = file.Path;
...
}
}
In foreach statement, filepath is not included when this condition openFileDialog.ShowDialog() gets true, you are getting only filename. To get filepath, use System.IO.Path.GetFullPath(FileName);, you could get filepath for the filename
So, I set up a file browser, fully working.
But now I want to take the end location where you went and put that location into a TextBox. Which can still be typed in by the user for if they want to manually type the file location.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException) { }
}
Console.WriteLine(size);
Console.WriteLine(result);
}
You can get the full path
textBox1.Text = file;
and the last folder name
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(file));
textBox1.Text = lastFolderName;
in your code you can use like below, if you want to use the location from another scope then make file variable global
string file = "";
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file; // for full location
textBox2.Text = Path.GetFileName(Path.GetDirectoryName(file)); // for last folder name
}
catch (IOException)
{
}
}
}
and then
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = file;
}
Hy everyone,
I would like to copy multiple selected files with openfiledialog to a folder which is defined as #"C:\TestFolder\"+ textBox1.Text. My problem is that somehow the program writes the textBox content in the file name too.
Please find below my code:
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "All files (*.*)|*.*";
od.Multiselect = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
if (!System.IO.Directory.Exists(targetPath)
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
{
System.IO.File.Copy(fileName, path + System.IO.Path.GetFileName(fileName));
}
}
}
Any input would be appreciated!
Try this one:
string Main_dir = #"C:\TestFolder\";
string Sub_dir = textBox1.Text + #"\";
string targetPath = System.IO.Path.Combine(Main_dir, Sub_dir);
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
System.IO.File.Copy(fileName, targetPath + System.IO.Path.GetFileName(fileName), true);
}
Backslash is missing
#"\"
These things are equivalent.
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
I would drop the first one for the Path.Combine call as it is portable and robust when it comes to the separators.
Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");