C#: Writing a RTF (Text) file to system drive - c#

I have a program which contains a richTextBox and a Button. Upon clicking the button, the program gets the text from richTextBox and saves it to a predefined location stored in a string variable.
If I change this location to C drive which is my System Drive, it won't allow me to do it and throws a System.UnauthorizedAccessException.
I am also the admininstrator of my PC. Is there any way that I can get permissions or work something out to solve this issue? Thanks in advance.
I use the following code
private void button1_Click(object sender, EventArgs e)
{
string temp = location;
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
file.WriteLine(this.richTextBox1.Rtf);
file.Close();
}

Trying to write files directly to the root of the c: drive often cause problems, such as the exception you're seeing.
Try storing your file somewhere else. A good way of getting a safe folder is to use the SpecialFolder enumeration: (change it to Desktop, MyDocuments, or whatever might be appropriate in your case)
string temp
= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myFile.txt")
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
Considering your update, try this instead:
string temp
= Path.Combine(#"C:\Users\MuhammadWaqas\SkyDrive", "myFile.txt");
As pcnThird suggested, you could save it to "myFile.rtf" instead and take advantage of the file type, assuming you're going to be opening the file and reading the contents outside of your app.

You have to specify a file name instead of a folder, try changing location to "C:\Users\MuhammadWaqas\SkyDrive\test.txt"

Check your location. You might be trying to write to a non existent or restricted location

Related

Open selected file from treeview in a richtextbox

My application consists of a TreeView a RichTextBox and a Button.
The TreeView displays contents(directories, folders and files) of my system.
The Button when pressed is supposed to take the selected file from the TreeView and display it in the RichTextBox.
I have used the following code:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath;
MessageBox.Show(a); //To check if it's taking the correct path
richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText);
}
The value in the string a is correct, that is TreeView.SelectedNode.FullPath returns the correct path which I confirm with the MessageBox.
However there is a runtime exception in the richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText) line.
It appends the path of the Debug folder before the actual selected file path(shown in the image), which leads to an exception.
All the files are stored locally.
How can I solve this problem?
It is because your tree nodes contains relative path to item instead of absolute.
How to prevent it? At first, you should store the full path (include drive name) in FullPath property.
If the path starts with the folder name, application tries to get the inner folder of current active folder (Debug). If the path starts with \ - app will seek the file in the root folder of current drive, if the path starts with drive name D:\ - app will seek the file on this drive. So, in your case, it will be better to pass absolute path always, it will exclude ambiguity while searching the file.
If the file should be stored relatively to the executive file, you should add some ..\ as prefix - it stands for 'going one level upper'
You can read this to get more familiar with windows pathname style.
After some research and trials I found the solution to this issue.
The reason behind this problem is that the code TreeView.SelectedNode.FullPath returns the path with an incorrect syntax.
Suppose the file you've selected in the TreeView has the path C:\Users\Admin\Desktop\test.txt
TreeView.SelectedNode.FullPath will return the path: C\Users\Admin\Desktop\test.txt which is syntactically incorrect i.e. it cannot be used directly in some other part of code.
The solution which I went for is, putting this output into a temporary string, and inserting :\\ in the 2nd place(1st index), thus making the syntax correct.(C:\\Users...)
Putting up the code I used just for reference:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath.ToString();
string b = ":\\";
string c = a.Insert(1, b);
richTextBox1.LoadFile(c, RichTextBoxStreamType.PlainText);
}
Hope this helps. Thank you for the assistance I received while solving this problem.

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

How do i access and create txt files in the same directory as the program in c#

http://pastebin.com/DgpMx3Sx
Currently i have this, i need to find a way to make it so that as opposed to writing out the directory of the txt files, i want it to create them in the same location as the exe and access them.
basically i want to change these lines
string location = #"C:\Users\Ryan\Desktop\chaz\log.txt";
string location2 = #"C:\Users\Ryan\Desktop\chaz\loot.txt";
to something that can be moved around your computer without fear of it not working.
If you're saving the files in the same path as the executable file then you can get the directory using:
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Normally you wouldn't do that, mostly because the install path will be found in the Program Files folders, which require Administrative level access to be modified. You would want to store it in the Application Data folder. That way it is hidden, but commonly accessible through all the users.
You could accomplish such a feat by:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
With those first two lines you'll always have the proper path to a globally accessible location for the application.
Then when you do something you would simply combine the fullPath and the name of the file you attempt to manipulate with FileStream or StreamWriter.
If structured correctly it could be as simple as:
private static void WriteToLog(string file)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
// Validation Code should you need it.
var log = Path.Combine(fullPath, file);
using(StreamWriter writer = new StreamWriter(log))
{
// Data
}
}
You could obviously structure or make it better, this is just to provide an example. Hopefully this points you in the right direction, without more specifics then I can't be more help.
But this is how you can access data in a common area and write out to the file of your choice.

How to backup a complete file?

What is the most efficient way to make a backup of a file when it's being opened into the program, so that when the user changes and saves it, there is always a way to go back?
Example:
private void open_click(object sender, EventArgs e)
{
ofd.DefaultExt = "";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileIn = ofd.FileName;
fileOut = Path.GetTempFileName();
string encoded = File.ReadAllText(fileIn);
etc. etc. etc
}
The file that gets loaded into the program needs to get backed up as backup_01 and put in the same folder as the original file. When backup_01 exists, backup as backup_02, and so on).
Examples are more than welcome!
I would generally create a copy of the file itself, place it in a "backup" folder, and apply some naming scheme to it to indicate its age.
Eg: folder/originalFile.xyz ==> folder/backup/originalFile_2013-04-14-12-48.bak
Update/afterthought: I think the efficiency of this will depend on the OS performing the Copy-operation, but it should in general not be too bad. Unless you have good reason to do so, I would avoid trying to add extra logic to do it more efficiently.
Update in response to comment:
I won't provide a detailed implementation here, but I'll try to point you in the right direction: Check out System.IO.File, specifically the methods Copy and Exists. (This list of other common IO-taks may also be useful)
With these, you should be able to check if a file exists (eg. if you already have "backup_1.xyz" in your backup-folder), and based on that, generate a new name for your next backup file.
Create a loop that replaces 1 with increasing numbers until you find a "free" filename, and then copy the original file to a new file with that name.
Good luck! :)

How to delete 0KB text file

1) I am new to c sharp,
I am having a problem ,
I know how to delete the file,
I am using this line of code to delete the file,
private void button2_Click(object sender, EventArgs e)
{
File.Delete(a);
}
I want to know how to delete 0KB file.
2)and one more thing i want to know how many path we can save for our application like ,
private void button2_Click(object sender, EventArgs e)
{
String a = (String)(Application.StartupPath + "\\TEMP");
}
I think there are more paths like Application.StartupPath ,can anyone pls say how many ways are there to save a path like Application.StartupPath .
There would be a great appreciation if someone could help me,
Thanks in Advance,
You delete a 0KB file just like you delete any other file (i.e., File.Delete is correct). If the file cannot be deleted, it is probably in use. You can use Process Monitor to find out which process is using the file.
Other special paths can be obtained using Environment.GetFolderPath with the SpecialFolder enumeration.
EDIT (after reading the comments): If you want to delete all 0-length files in the directory, you can
use Directory.GetFiles to get a list of all the files in the directory,
use FileInfo.Length to get the size of the files, and then
use File.Delete to remove certain files.
In fact, the MSDN page on FileInfo.Length contains an example that outputs a list of files and their sizes in a given directory. You should be able to adapt this example to delete all files with 0 length.
In regards to you first question - you delete a 0 length file the same way you do any other file:
File.Delete(pathTo0LengthFile);
Your second question doesn't make sense. You can save your file in any path on the drive that the account the application runs under has write permissions to.
There are several system and special folders that you can get the path of use Environment.GetFolderPath - perhaps that's what you mean.

Categories