C# System.UnathorizedAccessException on 2nd Button Click - c#

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.

Related

Using textbox to gather user's destination path for exporting a CSV in C# Windows application?

I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.

Hide/modify string in listView

I am making a program in which users can modify remote files. I put the selected files (depending on some predefined criteria) in a listView, but I display only the file names, not full filepaths.
The problem I get however, is that when a user would double-click on an item, it should open another window to modify that item.
private void listView1_DoubleClick(object sender, EventArgs e)
{
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Text+".txt");
Form3 passForm = new Form3();
passForm.ShowDialog();
}
private void Form2_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles("\\\\myremotserver\\ftp\\","*.txt", System.IO.SearchOption.AllDirectories);
foreach (string s in files)
{
listView1.Items.Add(Path.GetFileNameWithoutExtension(s));
}
}
The problem is, that the files are all in different subfolders, so if I leave the code as is, it will not display the correct content of the file. For example, the file is called test1.txt, it is placed in myremoteserver\ftp\testfolder\test1.txt, but with my program, it will try to find the file in myremoteserver\ftp\test1.txt.
What I am asking is, if it is possible to modify the listView in such a way, that the full file path is always saved, but only the file names are displayed? I do not want the user to see the complete file path of the files, just the file names.
Use the Tag property of the ListViewItem
So to create items...
foreach (string s in files)
{
ListViewItem lvi = new ListViewItem(Path.GetFileNameWithoutExtension(s));
lvi.Tag = s;
listView1.Items.Add(lvi);
}
Then in event handler...
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Tag +".txt);

How to delete file and that file is used by another process using C#

In my C# application I want to delete file in below scenario.
OpenFileDialog and select any .jpg file.
Display that file in PictureBox.
Delete that file if needed.
I already try while doing step 3 I set default Image to PictureBox just before delete but that is not work.
How can I delete file? Please suggest me.
// Code for select file.
private void btnSelet_Click(object sender, EventArgs e)
{
if (DialogResult.OK == openFileDialog1.ShowDialog())
{
txtFileName.Text = openFileDialog1.FileName;
myPictureBox.Image = Image.FromFile(openFileDialog1.FileName);
}
}
// Code for Delete file
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
//myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + #"\Images\defaultImage.jpg");
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Replacing the image sounds like a good idea - but don't forget to dispose of the old Image that's still holding the file open (and will, by default, until that Image is garbage collected - at some unknown time in the future):
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
var old = myPictureBox.Image;
myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + #"\Images\defaultImage.jpg");
old.Dispose();
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(It may also be possible to Dispose of the Image directly without replacing the image for the PictureBox - it depends on what else you're going to do after deletion - e.g. if the form on which the PictureBox appears is closing that you may want to let that happen first and then just directly dispose of the image).

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;

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