Get path to it and run process - c#

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.

Related

Create an error message if it cannot find the source path

I've created a class that copies everything in the file and paste it in a different location but I want to be able to add an error message if it cannot find the file path, in case it hasn't been set up on the PC.
I'm using System.IO. So what code would I need to make this check for the file path before actually starting the class?
You could either wrap your code in a try catch, or check if the path exists.
To check if the path exists:
if(Directory.Exists(path))
{
// logic goes here
} else
{
// error message
}
Here I check the path, and if it doesn't exist, I create it, later I check if a file type txt exist, and I create it too, and write on it. Look this complement, just in case →
string path = #"c:\NewFolder";
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
path += #"\Log.txt";
if (!File.Exists(path))
{
var strFile = File.Create(path);
File.SetAttributes(path, FileAttributes.Normal);
strFile.Close();
}
using (StreamWriter sw = new StreamWriter(path, true))
{
string texto = string.Empty;
texto += "\n Date: " + DateTime.Now.ToString("yyyy/MM/dd hh:mm");
sw.WriteLine(texto);
sw.Close();
}

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

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

Path with white spaces can't create a file using File.CreateText(filePath) c#

I'm developing a console application that parse xml files and generate a txt file. I have created the file path to store the new file, but this is having white spaces, like this:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
but I'm creating the path using:
string filePath = Path.Combine(temp, "fileName.txt");
while temp is the previous path. And when I call:
StreamWriter sw = File.CreateText(filePath);
Is giving this exception:
Could not find a part of the path: filePath
Can someone help me with this issue?? how can I create the file with this path?
there looks like a problem with you file path
try#"C:\Program Files\my path\fileName.txt"
Note: You've updated your question with the changes mentioned in the comments.
Your issue is probably that 'my path' doesn't exist as this console application works OK for me when run as an administrator. When not run I get an UnathorizedAccessException
class Program
{
static void Main(string[] args)
{
try
{
var temp = #"C:\\Program Files\\my path\\";
string filePath = Path.Combine(temp, "fileName.txt");
StreamWriter sw = File.CreateText(filePath);
Console.WriteLine("I got here");
}
catch (Exception)
{
Console.WriteLine("I didn't");
//
}
}
}
Use this:
string filePath = #"C:\Program Files\my path\fileName.txt"
You have single backslashes in the string. Make them double backslashes:
string filePath = "C:\\Program Files\\my path\\fileName.txt"

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