How can i replace path with file name? - c#

Hello i have to finish school project after another student.
And in whole program he used absolute path to file, the problem is it only works at one computer. Cuz this path is unique.
Could anybody tell me how can i replace this path just with file name?
string content = File.ReadAllText(filePath);
this.DocumentXml = XDocument.Parse(content);
this.xmlInfo = XDocument.Parse(content);
var groups = this.DocumentXml.Root.Elements("group");
foreach (var group in groups)
{
checkedListBox1.Items.Add(group.Attribute("name").Value);
}
// Adding data from your DNSFile to dataGridView1
hostsDataSet.Clear();
hostsDataSet.ReadXml(filePath);
dataGridView1.DataSource = hostsDataSet;
dataGridView1.DataMember = "item";
In this case "filepath" is text file with absolute path with file that he used.
Can you help me?
This is whole path to the file, that i create with Application.LocalUserAppDataPath: C:\Users\praktykant1\AppData\Local\WindowsFormsApplication1\WindowsFormsApplication1\1.0.0.0\test.txt
Problem in my case is that i have to create file that i use in program in AppData/Local folder.So on every computer the path will be different. And this program must work on every computer. Im just beginner so i am green in this subject.

This is precisely what config files are for... differences between environments in which the same code might execute.
Presumably the problem is that filePath is hard-coded, yes? Something like this?:
var filePath = #"c:\some\path\to\a\file.xml";
Instead, make that a configuration value. First add an entry to the App.config (or Web.config if this is a web application) in the appSettings node:
<appSettings>
<add key="filePath" value="c:\some\path\to\a\file.xml" />
<!-- any other settings already in place... -->
</appSettings>
Then use ConfigurationManager to get that setting. (You may need to add a reference to the System.Configuration assembly in the project.) Something like this:
var filePath = ConfigurationManager.AppSettings["filePath"];
You might also perform some error checking to make sure there's a value there at all (make sure filePath doesn't end up as a null or empty string, that is), make sure the file exists, etc.
At this point you can change the value in the config file without having to re-compile the code. So any new environment can set the config setting and use the application.

To get the file name of a path, just do this.
For example if your path is "C:\hello.txt", it becomes "hello.txt"
string fileName = Path.GetFileName(filepath);
If you do not like your file name to have any extensions
string fileNameNoEx = Path.GetFileNameWithoutExtension(fileName);
That way it becomes "hello"

If you set the variable filepath to be just the filename - it would look for this file in the directory where the executable file was started from (by default). This is called the working directory and you can find how to change the working directory online.
If you want to avoid using a full (or relative) path and just use the filename - expect it to be in that working directory.

In case of ASP.net you can do this,
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}

Related

How to check if a file exists or not in the directory the executable is?

How can I check if a file exists or not in the directory the executable is?
I know how I could code it like this.
string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}
But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones.
You are not creating the possible file path properly. Use Path.Combine like:
string path = Path.Combine(Application.StartupPath, "config.cfg");
You are getting a path without terminating \ from Application.StartupPath, later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails.
Just to show, the actual reason for getting the error, you can fix your code like:
string path = Application.StartupPath +"\\"+ "config.cfg";
But, do not use the above code, instead use Path.Combine to join multiple path elements.

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.

Write file to project folder on any computer

I'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").
Yes, just use a relative path. If you use #".\test.txt" ( btw the # just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.
You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.
Here is sample code:
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If you want to get the current folder location of your program use this code :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
Full code to write the data to the file :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");
if (!File.Exists(fileName))
{
// Create the file.
using (FileStream fs = File.Create(fileName))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}

Loading files in default Internet browser programmatically

I used this to load a file (html_file.html) from Resources
//string myFile = "C:\\Users\\...\\Resources\\html_file.html"; // this works
var myFile = Path.GetFullPath("html_file.html"); // this doesn't works
//myFile = myFile.ToString();
//myFile = myFile.Replace(#"\", #"\\");
//MessageBox.Show(myFile);
try
{
Process.Start(myFile);
}
catch (Win32Exception noBrowser)
{
if (noBrowser.ErrorCode == -2147467259)
MessageBox.Show(noBrowser.Message);
}
catch (System.Exception other)
{
MessageBox.Show(other.Message);
}
Can someone tell me what's wrong?
EDIT : This works
Build Action = Embedded Resource and Copy to Output Directory = Copy always
string myFile = #".\Resources\html_file.html";
but I still need to have the path Resources with the file. Is there any way to have the 'html_file' inside my .EXE file?
Quite obviously it cannot find the file in the current directory. Make sure the following are correct:
The file is included in your project and its Copy to Output Directory property is set to Copy always or Copy if newer.
Use Application.StartupPath to make sure you are pointing to correct directory, so the first line would become:
Code:
var myFile = Path.Combine(Application.StartupPath, "html_file.html");
In the first method you specify the exact path to your file.
In the second one you ask the framework to create a fullpath.
The framework need to start from somewhere and it choose to start from your current directory but the file is not present there

problem with opening a file in C#

What am I doing wrong in the following code?
public string ReadFromFile(string text)
{
string toReturn = "";
System.IO.FileStream stream = new System.IO.FileStream(text, System.IO.FileMode.Open);
System.IO.StreamReader reader = new System.IO.StreamReader(text);
toReturn = reader.ReadToEnd();
stream.Close();
return toReturn;
}
I put a text.txt file inside my bin\Debug folder and for some reason, each time when I enter this file name ("text.txt") I am getting an exception of System.IO.FileNotFoundException.
It is not safe to assume that the current working directory is identical to the directory in which your binary is residing. You can usually use code like the following to refer to the directory of your application:
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string filename = System.IO.Path.Combine(applicationDirectory, text);
This may or may not be a solution for your given problem. On a sidenote, text is not really a decent variable name for a filename.
If I want to open a file that is always in a folder relative to the application's startup path, I use:
Application.StartupPath
to simply get the startuppath, then I append the rest of the path (subfolders and or file name).
On a side note: in real life (i.e. in the end user's configuration) the location of a file you need to read is seldom relative to the applications startup path. Applications are usually installed in the Program Files folder, application data is stored elsewhere.
File.ReadAllText(path) does the same thing as your code. I would suggest using rooted path like "c:......\text.txt" instead of the relative path. The current directory is not necessarily set to your app's home directory.
You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.
My suggestions:
public string ReadFromFile(string fileName)
{
using(System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
return = reader.ReadToEnd();
}
}
or even
string text = File.OpenText(fileName).ReadToEnd();
You can also check is file exists:
if(File.Exists(fileName))
{
// do something...
}
At last - maybe your text.txt file is open by other process and it can't be read at this moment.

Categories