Getting File path from a open file dialog - c#

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)

Related

Copying text from one file into another results in a path denied exception

it says that the path to the file is denied.
looked for an hour no real answers.
please help.
private void btnSetText_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.InitialDirectory = Application.StartupPath;
dlg.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*"; //https://stackoverflow.com/questions/48151581/system-argumentexception-filter-string-not-valid
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtSetText.Text = dlg.FileName;
}
}
System.IO.File.WriteAllText(txtSetText.Text , text);
every thing is fine and valid, but at the line:
System.IO.File.WriteAllText(txtSetText.Text , text);
I keep getting access to path xyz is denied. How do I make it accessable?
You need to ensure that your destination file is not opened by another program and you need to be sure that your program user have the rights to open and edit this file.

Access to Path for Documents Folder denied when creating text document

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!");

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.

Unable to automatically save a file after reading it in. c#

I am attempting to create a note taking application (first Windows Forms application). So far I have managed to read a .txt file into a RichTextBox. I am trying to make the program create and save the .txt file containing the contents of the .txt file that was read in read in. So when the user adds text from a file it creates a new file in a notes folders that is in the root directory of application. Please see my code below. Any advice would be greatly appreciated. Cheers
private void button1_Click(object sender, EventArgs e)
{
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = op.FileName;
//create new .txt file contaning module notes
System.IO.StreamWriter file = new System.IO.StreamWriter("\\"+fileName);
file.WriteLine(fileName);
file.Close();
}
Tested and working
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = Path.Combine(Application.CommonAppDataPath, Path.GetFileName(op.FileName));
File.WriteAllText(fileName, "test");
wrap your streams, files (anything that implements IDisposable) in a using block:
using(var myfile = File. CreateText(path) ) {
myfile.WriteLine("hi");
}
it's not creating a file because the path is wrong

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