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.
Related
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.
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
In my soloution, for one of the projects I have to add a binary file and read its content in the form_load event.
As you can see in the picture I have added it to the appropriate project and have set the Build Action to Content and Copy to Output Directory as Copy Always.
Now can somone please tell me how how to access this file?
private void SetupForm_Load(object sender, EventArgs e)
{
//Find the path to file then
//READ THE FILE
}
Now you should find this file in your output directory after building your project. Given the right path to the file, you can access this file with any method you want.
Some methods can help you to get the path to the file:
Directory.GetCurrentDirectory();
Environment.CurrentDirectory
I'm not sure exactly what you're trying to do with the file, and that will determine your best approach here. As per the answer here you have a couple of options. To paraphrase:
Serialization
Binary Reader
I think the best method was this, so far:
So when I add the file to the project, it will be in the same folder as the exetubale file of project resides. So for getting the path (including the name of exetuable file I had to use Application.ExecutablePath and to remove the file name and have the pure path to the folder I had to use Path.GetDirectoryName() and finally add the filename I wanted to acces to this path, as you can see below:
var path = Path.GetDirectoryName(Application.ExecutablePath) + "\\YourFileName.bin";
The API you call to read the file depends upon the type of file. But the general pattern is like this.
private void SetupForm_Load(object sender, EventArgs e)
{
System.IO.Stream input = Application.GetResourceStream(new Uri #"/MyApp;component/content.bin", UriKind.Relative)).Stream;
BinaryReader binaryReader = new BinaryReader(input);
}
You can directly readbytes from the file attached as resource.My resource in this example is SampleWordnew document.
byte[] bob = ReadBytesfromResources.Properties.Resources.SampleWordnew ;
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! :)
I am asking because I am working on a project for school. Yes this is homework. But, I'm trying to understand a little bit more, though.
This is one example of what is being asked.
• When the user clicks the “Save” button, write the selected record to the file specified in txtFilePath (absolute path not relative) without truncating the values currently inside.
This is what I have,
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter myWriter = new StreamWriter(saveFileDialog1.FileName);
myWriter.Write(txtFilePath.Text);
myWriter.Close();
}
}
Now, I don't understand if I am doing this right. I know when I save it to my desktop and I delete it from my listbox and when I try to reload it again nothing shows up. This is what I have on my form,
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
txtFilePath.Text = openFileDialog1.FileName;
txtFilePath.Text = myReader.ReadToEnd();
myReader.Close();
}
}
And this is the load,
private void Form1_Load(object sender, EventArgs e)
{
string[] myFiles = Directory.GetFiles("C:\\");
foreach (string filename in myFiles)
{
FileInfo file = new FileInfo(filename);
employeeList.Items.Add(file.Name);
}
//...
Can someone please help me make sense of this?
Say you were giving directions to a spot. You have two methods you can describe getting to the location:
Relative to where you stand,
Relative to a landmark.
Both get you to the same location, but the former doesn't always work ("take a left, then a right, go through two lights then take another right" wouldn't necessarily work from the next town over, but works from where you stand). That's essentially the difference.
If you have C:\Windows\System32, that's an absolute path. If you have Windows\System32, it will only work so long as you're starting from C:\. If you start in C:\Program Files you would need a ..\ to get there correctly.
However, no matter where you are on the hard drive, C:\Windows\System32\ is a definitive way to get to that folder.
It's actually a simple distinction. A relative file path is going to be a structure based around a root node; and an absolute path is going to be a structure based on a non ambiguous location. That sounds kind of wonky, but it's actually pretty simple.
Here are some examples:
Absolute Paths
C:\inetpub\yourapplication\default.aspx
http://www.yourapplication.com/default.aspx
These paths are absolute because they are non ambiguous. Example 1 shows an absolute file path, and example 2 shows an absolute URL.
Relative Paths
./../script/something.js
~/default.aspx
A relative path specifies a location based on some known ahead point of reference. So in example 1, you know to go up one directory, then down into a directory called script, then to a javascript file. In example two, you are specifing the aspx page contained within the root of your application.
So, germane to your specific problem, you want to write a file to a specific absolute path, which means it needs to be a non ambiguous location.
An absolute path is the whole path name required to access the location in the file system.
For example: C:\Program Files\Internet Explorer\iexplorer.exe
Where as a relative path is in relation to some landmark, usually your main executable files location or the 'start in' location set when you open the program.
For example if your main executable is in C:\Program Files\ the relative path to iexplorer.exe is Internet Explorer\iexplorer.exe.
This is done usually when you don't always know where the file will absolutely be, like which drive letter it will be installed in or which folder it will be under.
However for a good example, if your file came with your program and you know your programs installation structure, you can use relative pathing to find all your files no matter where your program is installed as opposed to abolute pathing where your program would need to be installed in the exact same location each time.