Directory.Exists() always returning false? - c#

I am experiencing a strange problem at the moment with my C# code. I am attempting to use the folderBrowserDialog to retrieve the path of a folder selected by the user.
Once the user clicks a button to confirm the selection (the chosen path of which appears in "textBox1"), if the folder location is found, should return the message "connection established" (if the directory/file found) or "no connection found" (if the file/directory does not exist).
For some odd reason however, the code always seem to return false when checking if the directory exists - and yes, it does exist. My application requests admin rights in it's manifest file as I thought this would solve the problem, so I'm still stumped on this one.
private void button1_Click(object sender, EventArgs e)
{
//BROWSE
folderBrowserDialog1.ShowDialog();
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
private void button2_Click(object sender, EventArgs e)
{
var path = textBox1.Text + #"\" + "connection.pss";
//ESTABLISH CONNECTION
if (textBox1.TextLength > 0)
{
if (Directory.Exists(path))
{
connectionstatus.Text = "CONNECTION ESTABLISHED!";
//SET UP VARIABLES
}
if (!Directory.Exists(path))
{
connectionstatus.Text = "NO CONNECTION FOUND!";
}
}
}

That directory doesn't exist. That file exists. :)
Use File.Exists instead.

Connection.pss is not part of the directory. Try either just checking the directory or use File.Exists()

Related

C# System.UnathorizedAccessException on 2nd Button Click

The button1_Click Event (Copy PDF's to new location) works perfectly when the button is clicked and the code is executed the 1st time;
however, upon clicking the button a second time (with same text box entry), it throws the following error:
System.UnauthorizedAuthorizedAccessException: Access to the path "\share\drive....
Obviously, I don't want this to be able to execute twice during a session, given the same text box entry. Before I tackle that, I would like to fix this exception error. Am I erroneously leaving the path open?
Code updated to show solution:
public static string Case_No;
namespace CEB_Process
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//===============================
// TEXT BOX ENTRY
//===============================
private void textBox1_TextChanged(object sender, EventArgs e)
{
Form1.Case_No = textBox1.Text;
}
//==============================
// CHECK if Direcotry Exists
//==============================
public void CreateIfMissing(string path)
{
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
//Added
var permissions = new DirectoryInfo(path);
permissions.Attributes &= ~FileAttributes.ReadOnly;
MessageBox.Show("The directory was created successfully");
}
}
//=================================
// MOVE Violation PDF's Button Click
//==================================
private void button1_Click(object sender, EventArgs e)
{
//Declare Source path directory from text box entry
string sourcePath = string.Format(#"\\share\drive\etc{0}", Case_No);
string targetPath = string.Format(#"\\share\drive\etc{0}", Case_No);
try
{
//Call Method to Check/Create Path
CreateIfMissing(targetPath);
//Get TRAKiT Violation PDF's from source
foreach (var sourceFilePath in Directory.GetFiles(sourcePath, "*.pdf"))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
File.SetAttributes(destinationFilePath, FileAttributes.Normal);
}//End For Each Loop
MessageBox.Show("Files Copied Successfully!");
}//end try
catch (Exception x)
{
MessageBox.Show("The process failed", x.ToString());
}
}//End Button Module
}//End Namespace
}//End Class
I also had the problem I added the following line of code before and after a Copy / Delete.
File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);
(PS: Taken from Why is access to the path denied?)
I suppose you're using File.Copy without overwriting the selected file.
That means the file is getting copied and it's temporarily locked by OS, and then it's not open to modifications (read-only). This is the reason of your UnauthorizedAccessException.
Check if you can accessthe file first.

Prevent user from browsing elsewhere in an OpenFileDialog

What I need to do is prevent users from browsing anywhere else then where I declare them to browse.
for example I have: ofd.InitialDirectory = Location; on button click.
Location for example being C:\Users\Chris\Pictures.
The thing is that I know that some users will try be clever and might go selecting things outside that folder I declare. Is there any way to prevent that from happening?
Possible workaround:
Just an if statement checking if the location of the selected file starts with the same Location I start them off in.
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
string newPath = #"C:\Users\Chris\Pictures";
ofd.InitialDirectory = Location;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (ofd.FileName.Contains(Location))
{
textBox1.Text = ofd.FileName;
}
else
{
MessageBox.Show("Please select a file that is located in the specified location (" + Location + ")"
, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You can't prevent users from navigating to another folder, you have to build an own OpenFileDialog if you want to do that. You can prevent though that the file isn't accepted.
You have to handle the FileOk event for that. You can check if the parent directory is the one you want it to be.
Something like this:
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string[] files = openFileDialog1.FileNames;
foreach (string file in files )
{
if (Path.GetDirectoryName(file) != yourRequiredPath)
{
e.Cancel = true;
break;
}
}
}
This is not possible.
You can't restrict users to prevent them to browse elsewhere where you don't wish to.
One possible way to fix this is to write your custom open dialog box with custom validations.
If you really want to prevent navigation in the file dialog the only way to do it would be to use the Common Item Dialog, provided by COM1, and give it an IFileDialogEvents and implement the OnFolderChanging event. To allow navigation, return S_OK and to deny navigation return something else.
1 "Provided by COM" as in the component object model, not some third party.

How do I show a directory path in a textbox when selected by the user?

First, I am using Visual Studio 2013 and coding in C# to develop a Windows Form Application. I have added the "System.IO" namespace.
I need to show a directory path in a textbox when selected by the user.
The code works correctly to where the user selects a folder from a popup
and presses the OK button, which then displays the number of files within
that folder -- but the folder path does NOT get displayed as I desired.
Code looks like this:
private void button1_Click(object sender, EventArgs e)
{
//
// This event handler was created by clicking the button in the application GUI.
//
DialogResult button1_Click = folderBrowserDialog1.ShowDialog();
if (button1_Click == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// A message pops up and identifies the number of files found within that folder.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string path;
path = folderBrowserDialog1.SelectedPath;
// folderBrowserDialog1.ShowDialog(); // NOT SURE ABOUT USING THIS!
textBox1.Text = path;
}
You could just add this to the end of your button1_Click method (inside the if block):
textBox1.Text = folderBrowserDialog1.SelectedPath;

How to check for a specific file and delete it

i am using a C# winform in which i wanted to search for a particular file in a folder and i want to delete it.
How can i do this. i am trying with the below codes.
private void button4_Click(object sender, EventArgs e)
{
string Filename = img_path.Text; // here i have the filename "sample.grf"
if (Directory.GetFiles(#"E:\Debug").Where(x => x.Name == Filename).Any()) // getting error here
{
// i want to search here in above folder and delete the file.. how to do this
System.IO.File.Delete(/dont know how to delte the particular file);
}
}
please help out
This is simply done this way:
File.Delete(Path.Combine(#"E:\Debug", Filename));
No need to check if the file exists first. If it doesn't, File.Delete will simply do nothing.
If you may have any security concern (like a user entering ..\SomethingElse\Important.doc for instance), you need to ensure the field only contains a file name. One way would be:
if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
return;
So your whole function may look lie this:
private void button4_Click(object sender, EventArgs e)
{
string Filename = img_path.Text;
if (string.IsNullOrEmpty(Filename))
return;
if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
return;
File.Delete(Path.Combine(#"E:\Debug", Filename));
}
Also, button4_Click is not a very friendly name to maintain. You may want to consider renaming the button and that function to something meaningful.
If you know the file, just Delete() it:
File.Delete("C:\\mypath\\myfile.txt");
There is no exception thrown for a file that already does not exist, according to MSDN.

Having trouble creating a new folder on user input Visual Studio 2010 C#

Essentially I have a button and a text box and when the user inputs text and hits the button i want it to create anew folder in a selected destination, ive got my code currently and cant figure out why it wont work
private void button1_Click(object sender, EventArgs e)
{
if (!Directory.Exists("C:\\Users\\Ben\\Documents\\CreateDirectoryTest" + Searchbox.Text))
{
Directory.CreateDirectory("C:\\Users\\Ben\\Documents\\CreateDirectoryTest" + Searchbox.Text);
}
}
am i missing something? help would be really appreciated
Don't concatenate file system path's manually. Use the methods of System.IO:
private void button1_Click(object sender, EventArgs e)
{
const string path = "C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\";
var directory = System.IO.Path.Combine(path, Searchbox.Text);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
}
I assume you're trying to check for a subdirectory of CreateDirectoryTest and create a directory inside of it if not. The way you're concatenating the string, if Searchbox.text is "TheFolder" for example, your string would end up looking like this:
C:\Users\Ben\Documents\CreateDirectoryTestTheFolder
You can either add a \\
if (!Directory.Exists("C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\" + Searchbox.Text))
{
Directory.CreateDirectory("C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\" + Searchbox.Text);
}
Or just use Path.Combine:
string path = System.IO.Path.Combine("C:\\Users\\Ben\\Documents\\CreateDirectoryTest", Searchbox.Text);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}

Categories