Directory could not be found - c#

I have recently started to get an error which states my directory can not be found I have tried a number of ways to solve this but have yet to find a solution.
The method should allow the user to select an image for their computer and add it to a folder called images inside the applications folder structure. The problem is that when using the File.copy(imageFilename, path); it throws the error. I have tried changing the path and you will see from the code snip it. It is even doing it when the program itself has passed the file path for the application and is still throwing me the error.
this is the method.
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
System.IO.File.Copy(imageFile.FileName, path);
}
}
}
I am using VS2013 and have included the using Microsoft.win32
Any further information needed please ask.
Thanks

There are 2 things need to be taken into consideration
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You wont need it
System.IO.File.Copy(imageFile.FileName, path); // Copy Needs Source File Name and Destination File Name
}
}
}
string path = AppDomain.CurrentDomain.BaseDirectory; You won need this because the default directory is your current directory where your program is running.
Secondly
System.IO.File.Copy(imageFile.FileName, path); Copy Needs Source File Name and Destination File Name so you just need to give the file name instead of path
so your updated code will be
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
System.IO.File.Copy(imageFile.FileName, SomeName + ".jpg"); // SomeName Must change everytime like ID or something
}
}
}

I'm not sure if that's the problem, but the File.Copy method expects a source file name and a target file name, not a source file name and directory: https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
So, to make this work, in your case you'd have to do something like the following (namespaces omitted):
File.Copy(imageFile.FileName, Path.Combine(path, Path.GetFileName(imageFile.FileName));
Note that this will fail if the destination file exists, to overwrite it, you need to add an extra parameter to the Copy method (true).
EDIT:
Just a note, the OpenFileDialog.CheckFileExists does not return a value indicating if the selected file exists. Instead, it is a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. So instead of checking this property after the dialog is closed, you should set it to true before you open it (https://msdn.microsoft.com/en-us/library/microsoft.win32.filedialog.checkfileexists(v=vs.110).aspx)

Related

I am unable to update my C# string variable

New to C#. I am trying to create a WinForms application to run different batch files. Due to the different path of the batch files for everyone (depending on where they store it), I am planning to let user select their path when they first start the WinForms.
I have tried several ways to save the path into a variable, then plan to use the variable to with Process.Start
Below are a part of my codes:
private void buttonTest_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
string filePath = "a";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = openFileDialog.FileName;
labelTest.Text = filePath;
Properties.Settings.Default["filePath"] = filePath;
Properties.Settings.Default.Save();
}
}
I'm constantly receiving an error in my if statement, cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter.
May I know what am I doing wrong? Appreciate any advices!

throwing UnauthorizedAccessException when accessing an image file

I have a problem with accessing and copying an image file. Here my code
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
string fileName = "";
fileName = openFileDialog1.FileName;
string newPath = #"C:\Users\grafik5\source\repos\ConsoleApplication1\x64\Debug";
string newFileName = #"image";
string ext = Path.GetExtension(fileName);
openFileDialog1.Dispose();
newPath = Path.Combine(newPath, newFileName + ext);
if (fileName != "")
{
try
{
FileSecurity oFileSecurity = new FileSecurity();
oFileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(fileName, oFileSecurity);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Error");
}
File.Copy(fileName, newPath, true);
Process process = new Process();
process.StartInfo.FileName = #"C:\Users\grafik5\source\repos\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe";
process.Start();
process.WaitForExit();
flag1 = true;
}
}
I don't know what I need to do. My program always throws the error message.
Another process will read the copied image. It will do image processing.
There is no problem with the process of working. I checked it.
Error is at File.SetAccessControl(fileName, oFileSecurity);
Any young Codeling Jedi should have looked at the documentation, which i assume you have. However -
File.SetAccessControl Method (String, FileSecurity)
Applies access control list (ACL) entries described by a FileSecurity
object to the specified file.
Exceptions
UnauthorizedAccessException
The path parameter specified a file that is read-only.
This operation is not supported on the current platform.
The path parameter specified a directory.
The caller does not have the required permission.
This is probably a permissions thing. The easiest fix, is make sure your application has the appropriate permissions to do this.
Either
Elevate your app by running it as Administrator,
Give your user the appropriate permissions to set the ACL
However it should be wise and prudent, to check if the other conditions apply

Display Filename in button text

How to get the string in the button text?
private void btn_open_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
ReadCSV(openFileDialog1.FileName);
btn_open.Text = "filename here";
string targetdirectory = "D:\\Projects";
string filename = Path.GetFileNameWithoutExtension(target directory);
}
thanks for your help
When you select a file using OpenFileDialog, the OpenFileDialog.FileName contains the full path of the file selected.
Path.GetFileNameWithoutExtension() does just that, getting the file name without extension. However you need to pass an actual file path, not a directory. If you pass a directory path, it will simply retrieve the innermost directory name which is not what your desired outcome.
So what you should do is;
Get file name from OpenFileDialog.
Pass that to the Path.GetFileNameWithoutExtension() method.
Set the resulting string as the button text.
Also the correct usage of ShowDialog() is to check the return value; it returns true if the user clicked OK button, and false otherwise.
if(openFileDialog1.ShowDialog() == true)
{
string file = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
btn_open.Text = file;
}

Multiple file upload without full path

I'm trying to upload multiple files and just get the filename of them.
When I'm trying to do that it just uploads one file.
So it uploads the files with the full path(And it works).
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames);// <-- this works, but here I get the full path
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
And so I get just the Filename but it uploads just one File:
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, System.IO.Path.GetFileNameWithoutExtension(CoreClass.OPENDIALOG.FileName)); // <-- Doesn't work. Just one File.
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
OK, If you are developing WinForms app then you are using OpenFileDialog which contains 2 properties:
FileName gets or sets a string containing the file name selected in the file dialog box.
FileNames gets the file names of all selected files in the dialog box.
Then first one will never contains few files and you should use it only in Multiselect = false; mode.
If you need to show all file names in one textbox then you can use String.Join method and LINQ to enumerate collection and get file name without extension for each element:
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames.Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray()); // <-- Doesn't work. Just one File.

ExtractToFile vs ExtractToDirectory

I have some code that is extracting a file to a directory. In the code below Global.fullpath is the full path to the file its self where as Global.path is the path to the directory. This code works:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
ZipFile.ExtractToDirectory(Global.fullPath, Global.path);
}
However I am trying to do an overwrite if any files exist so I have this code which doesn't seem to extract anything even when there are no existing files:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
using (ZipArchive archive = ZipFile.OpenRead(Global.fullPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
AppendTextBox("Extracting file: " + entry.FullName + "...\r\n");
entry.ExtractToFile(Path.Combine(Global.path, entry.FullName), true);
}
}
}
Based on the comments, if you're trying to extract a directory ExtractToFile() is not going to do what you expect. Directories can't be easily overwritten like files. I think you have two options:
Check if the directory specified by FullName exists, and delete it before writing.
Check if the directory specified by FullName exists, and then rename your folder you're going to write something like FullName = FullName + "_Copy";
Make sure you check if the combined path is a valid filename. The ExtractToFile method expects a path that ends with the filename, and some Zip archives can contain folders. In such a case, the entry.FullName property results in an invalid path.

Categories