Access to Path for Documents Folder denied when creating text document - c#

I am trying to make a text file in my documents
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamWriter sw = File.CreateText(path);
sw.WriteLine("Hello!");
}
It says that path is denied

You're getting an access denied error because File.CreateText() expects a full path to the file that should be created. The code is giving it the path to your Documents folder. Since that path already exists and is a folder, that is the cause of the access denied error.
You should change path to point to a non-existent text file first. Also, StreamWriter.Dispose() needs to be called in order to close the file (this is typically done with a using statement).
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, "MyFile.txt");
using(StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello!");
}
}

You have not given the path to the file you are trying to create; only the folder itself. Instead you could do something like
using (StreamWriter sw = File.CreateText(path + $"\hello.txt"))
sw.WriteLine("Hello!");

Related

Access denied error when trying to save file to directory

I am trying to write a file on button click event but getting an unauthorized error when trying to do so.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
{
string path = #"c:\program files\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
Getting the error by:
using (StreamWriter sw = File.CreateText(path))
Not sure what i am doing wrong? Could someone please help?
Thanks
By default in Windows a user or a programm started by a user can't write files to every location on a Windows pc.
Maybe try saving your file to a different location.
If that doesn't cut it for you, then you may need to look into running your programm at an elevated permission level
If you just want to save a file for your application the tippical place to do so would be the AppData Folder. The tipcal way of getting its path goes somthing like this:
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"/MyApplicationFolder";
You should change your path to authorize folder like :
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

How to find and copy .pdf file to clipboard

I'm trying to copy a pdf file to the clipboard so I can later paste it by Ctrl+V.
The following code can find a file but I'm not sure how to copy it to the clipboard.
How can I copy a pdf file once it is found?
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
Clipboard.SetDataObject(file);
}
I get error:
An unhandled exception of type 'System.ArgumentNullException' occurred in PresentationCore.dll
EDIT: I also tried the following, I don't get any errors but it doesn't copy the file.
EDIT: The following code does work, I was not putting the right path, I like jasttims answer better though.
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
var dataObj = new DataObject();
string[] fileName = new string[1];
fileName[0] = file;
dataObj.SetData(DataFormats.FileDrop, fileName, true);
Clipboard.SetDataObject(dataObj, true);
}
Try using the "Clipboard" class.
It features all the methods necessary for putting data on the Windows clipboard.
StringCollection paths = new StringCollection();
paths.Add("c:\file.pdf");
Clipboard.SetFileDropList(paths);

Get path to it and run process

How to get path by environment variable to get file:
string path = (#"%ProgramData%\\myFolder\\textdoc.txt");
to run file by environment variable path:
Process.Start(#"%ProgramData%\\myFolder\\file.exe");
Here is how you can create folder,file and write text in it. Once file is created and written, it will be opened in notepad.
private void button1_Click(object sender, EventArgs e)
{
string basePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myDir = Path.Combine(basePath, "myFolder");
if (!Directory.Exists(myDir))
{
Directory.CreateDirectory(myDir);
}
string myFile = Path.Combine(myDir, "textdoc.txt");
using (FileStream fs = File.OpenWrite(myFile))
{
using (StreamWriter wrtr = new StreamWriter(fs, Encoding.UTF8))
{
wrtr.WriteLine("This is my text");
}
}
Process.Start("notepad.exe", myFile);
}
Note : Way file is created and written in above code will always overwrite file content. If you need to append new content then you should use different constructor of StreamWriter and pass append parameter as true.
Also you need admin permission to create folder/file inside "ProgramData" folder.

Getting File path from a open file dialog

I want to make a button that
opens a file from some location in file system,
gets its file path,
pass the file path like an argument to a method
open that file and do something with it.
I've made a button like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open XML file";
fDialog.Filter = "XML files|*.config";
fDialog.InitialDirectory = #"C:\";
fDialog.ShowDialog();
}
I already made a method that reads from hard-coded location, but can someone help me about that file path part variable?
Method reads file with XmlTextReader like this:
private void ReadAdvancedConfigFile()
{
XElement root = null;
root = XElement.Load(new XmlTextReader(#"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config"));
}
So basically I want to put new file path for some file founded by OpenFileDialog in root variable.
Change this line:
fDialog.ShowDialog();
To:
bool? control = fDialog.ShowDialog();
if(control.Value)
{
var filePath = fDialog.FileName;
ReadAdvancedConfigFile(filePath)
}
Also you should change the method signature
private void ReadAdvancedConfigFile(string path)

File Copy in C#.Net

I'm trying to build a copier so that you use the openFileDialog to chose a file and then the folderBrowserDialog to choose the location to copy it to.
The problem I'm having is that when I use File.Copy(copyFrom,copyTo) it gives me an exception that I can't copy to a directory.
Is there anyway around this, or am I just missing something stupid and noobish. I've tryed useing openFD for choosing both locations and have just tried using the folderBD to see if it made a difference.
I know there should be if statements there to catch the exceptions but this is a rough draft of the code to get working 1st.
Thanks in advance for the help, code attached.
// Declare for use in all methods
public string copyFrom;
public string copyTo;
public string rootFolder = #"C:\Documents and Settings\cmolloy\My Documents";
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = rootFolder;
openFD.FileName = "";
openFD.ShowDialog();
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyDocuments;
this.folderBD.ShowNewFolderButton = false;
folderBD.ShowDialog();
DialogResult result = this.folderBD.ShowDialog();
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
private void btnCopy_Click(object sender, EventArgs e)
{
// copys file
File.Copy(copyFrom, copyTo);
MessageBox.Show("File Copied");
You have to append the file name to the directory path. Do this:
string destinationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinationPath);
(with this you'll copy selected file to another directory with the same name of the original one and it'll throw an exception if the same file already exist in that directory)
Edit
Side note: do not hard code the path in your source code, use this:
rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
to get the path of current user's documents folder.
Do this:
File.Copy(copyFrom, Path.Combine(copyTo, Path.GetFileName(copyFrom)));
File.Copy needs to know the full path of the new file you want, including the file name. If you just want to use the same file name, you can use this to append the file name to the path:
copyTo = Path.Combine(copyTo, Path.GetFileName(copyFrom));

Categories

Resources