How to check for a specific file and delete it - c#

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.

Related

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 can I pull a destination from a textbox? C#

I have a textbox that generates a code based on the selections made by the user. I would like each possible code to correlate with copying and moving a folder into another. The folder is chosen by another textbox that allows the user to manually select the path for the new files to be moved to. What I am looking to do is set up a string of if/else if statements for each of the possible codes from textbox1. Take a look at my code below and see wha tyou find. Everything seems to work except for my statements uder
Private void button1_click...
private void button1_Click(object sender, EventArgs e)
{
string destination = textBox1.Text;
if (textBox2.Text == "111")
String sourceFile = (#"C:\Program Files (x86)\OrganizerPro\TFSN Internal Advisor to SWAG PPW");
System.IO.File.Move(sourceFile, destination);
}
Your immediate problem might just be one of scoping, it looks like you try the move even if the if failed to set the value.
A list of If/else is not a very maintainable solution, you'll need to rebuild and redeploy each time the list of possibilities changes. Avoid this by reading the list from something that is external to the application.
However, what you describe is essentially a mapping between a code and a filename.
If your mapping really is static and you're happy for it to be baked into the application then you could define the mapping like this
private Dictionary<string, string> mapping = new Dictionary<string, string>
{
{ "111", #"c:\Program Files\File 1.txt" },
{ "112", #"c:\Program Files\File 2.txt" },
{ "113", #"c:\Program Files\File 3.txt" },
};
You can retrieve values using some simple Linq
var codeLookup = mapping.FirstOrDefault(kv => kv.Key == textBox2.Text);
if (codeLookup.Key != null)
{
System.IO.File.Move(codeLookup.Value, destination);
}
Your question is not very clear. But there is something not logic in your code. this is a code behind method so change the method's access modifier from private to protected or public cause the event click does not reach this method
private void button1_Click(object sender, EventArgs e)
to
protected void button1_Click(object sender, EventArgs e)

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);
}

Writing Something to a File then loading it again

Okay so i wanted to know how i would take something that is in a textBox, then i press a button, the contents of the textBox will be saved to a file location, then when i load the .exe back up, the contents will reappear in the textBox.
This is what i have so far
private void button3_Click(object sender, EventArgs e)
{
File.WriteAllText(#"C:\Application.txt", textBox1.Text);
}
^To Write it to a file location, I have tried this multiple times but it doesnt seem to want to make the file on my C:.
private void Form1_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = File.ReadAllText(#"C:\Application.txt", Encoding.ASCII);
}
catch
{
}
^To Load the file then inject it back into the textbox it came from
Any and all help is appreciated,
Thanks.
You likely get an exception when trying to write to your C drive because it requires administrative access. Try running Visual Studio as Administrator (therefor the app will run as admin when kicked off from VS) or try writing to another location. Your code is all fine. The Encoding.ASCII bit is unnecessary though and I recommend removing it (more than likely that's not the encoding you will write the file in).
Trying to write directly to the C: drive can cause problems.
Try writing to a location that you definitely have write access to. You could use the ApplicationData directory (for application files unique to the current user), or use SpecialFolder.MyDocuments if you prefer.
private string applicationFilePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "Application.txt");
private void button3_Click(object sender, EventArgs e)
{
File.WriteAllText(applicationFilePath, textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = File.ReadAllText(applicationFilePath, Encoding.ASCII);
}
I would do something like this:
using System.IO;
private void button3_Click(object sender, EventArgs e)
{
using (var stream = new FileStream(#"C:\Application.txt", FileMode.Create))
using (var writer = new StreamWriter(stream, Encoding.ASCII))
writer.Write(textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
using (var stream = new FileStream(#"C:\Application.txt", FileMode.Open))
using (var reader = new StreamReader(stream, Encoding.ASCII))
textBox1.Text = reader.ReadToEnd();
}
I think this method gives you more control on your content. Try to explore the contents of FileMode enum, and make sure to add your using System.IO; directive.
Be careful not to confuse the using statement with the using directive.
Also, always remember to dispose/close your stream when done to ensure that the data has been flushed and that the file is no longer in use by your application. Here, the using statement does the job of disposing when the stream is no longer in use.
EDIT: As mentioned by the other posts, writing to the C: directory causes problems on newer operating systems due to Admininstrative Access restrictions. Make sure to write to different drives/folders that you definitely have access to.
// Current User
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Application.txt");
// All users
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application.txt");

Directory.Exists() always returning false?

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()

Categories