I've been teaching myself how to code lately because I am bored. I am trying to load an XML file on startup and put the contents of that file into a listbox, then save the contents of the listbox to the file on close. That's exactly what I have now. However I want to be able to load from AppData as well as save back to the AppData folder without having to type the full path. I've tried using "%AppData%/Roaming/MyApp/data.xml" but that does not work and throws a exception.
Here is what I have now:
StreamReader sr = new StreamReader("data.xml");
line = sr.ReadLine();
while (line != null) {
Streamers.Items.Add(line);
line = sr.ReadLine();
}
Streamers.DataSource = line;
Streamers.Sorted = true;
sr.Close();
Console.ReadLine();
You can use GetFolderPath
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
Also you can check this answer for more information.
Update
Notice that you need Administrator rights to access this folder.
For Access denied error check these two answers:
Number one
The directory %AppData% is a system-protected directory. Windows
will try to block any access to this directory as soon as the access
was not authorized (An access from another user than the
Administrator).
Number two
I would use System.IO.Path.Combine(...) instead of
string.Conact(...) in this situation. Like this...
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Programım");
Related
im trying to read a folder from a remote machine, inside this folder there are many txt files.
The machine is writing every time new datas inside the folder.
string str = "";
try
{
DirectoryInfo d = new DirectoryInfo(#"\\192.168.1.209\user\HST\");
FileInfo[] Files = d.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
}
catch (Exception pp)
{
System.IO.File.WriteAllText(GlobalVariables.errorFolderLocation + "erroreLettura.1.209.txt", pp.ToString());
}
This is my code, I don't understand how to get these datas, because i get this error: "the system call level is not correct".
For example, if i try to delete the folder or a file, i get error because it's already used by another process.
So, is there a solution to "bypass" this error?
EDIT 1:
I need read every row of every file, i get the error on DirectoryInfo.
If i acces on the folders and files it works fine.
I need read this folder/files in 3 different machine, but only in this (192.168.1.209) not working, and its the only machine where i get error when i try to delete a file
Unfortunately, you are not able to delete a file which is in use by another process or delete a folder that contains a file in use, or whatever other operation that has not been specified to be accessed on the other process. In order to achieve this, the process which has the file in use, must open it with a share access, FileShare from System.IO .NET library.
Problem:
I am trying to create a text file from a web service (local host), but on creation it gets the null argument error for path location. Now I am still using 2012 and was under the impression the code I gave would return the path name, but just returns null.
Aim:
Create a new file if one doesn't exist.
Get the path of the file for future use.
Question:
What are the visual studio 2012 C# methods for creating a text file? I find allot of sources but the code doesn't seem to work with 2012.
My Code:
//Create a file name for the path
string path = System.IO.Path.Combine(CurrentDirectory, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
}
Get the file path using Server.Map path
string FolderPath = Server.MapPath("~/App_Data");
string file = Path.Combine(FolderPath, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(file))
{
System.IO.File.Create(file);
}
Also check if the IIS user have permission to write on that folder (Add permission to the application pool user)
If you are trying to write something on a txt file, these piece of code does. No need to create a file if it is not exist. These code will create a file automatically if it not exists.
public static void LogMessage(string sFilePath, string sMsg)
{
using (StreamWriter sw = File.AppendText(sFilePath))
{
sw.WriteLine(string.Format(#"{0} : {1}", DateTime.Now.ToLongTimeString(), sMsg));
}
}
Are you sure CurrentDirectory value is right?
If you want visit current Web Service root dir can use like AppDomain.CurrentDomain.BaseDirectory.
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.
I wrote a simple console tool that reads a file and then writes something out. I intend to just drag and drop files and then out pops the output in the same directory as the input file.
All of the testing works, and when I call it from command-line, everything comes out as expected. However, when I tried dragging and dropping it in explorer, no files were created.
I did a search through the system and found that they were all dumped at Documents and Settings under my user folder, and when I printed out the full path that's what it said.
Which is weird. Wouldn't Path.GetFullPath return the absolute path of the input file? Instead it looks like it just combined that user directory path to the input's filename.
EDIT: here's the code. I feel like I've made a logic error somewhere but can't seem to see it.
filename = System.IO.Path.GetFileName(args[i]);
abspath = Path.GetFullPath(filename);
dirpath = Path.GetDirectoryName(abspath);
....
Console.WriteLine(dirpath);
Path.GetFullPath should return the absolute path of the path string you pass in.
Path.GetFileName(string path) only returns the filename and extension of the file you pass in. For example, System.IO.Path.GetFileName("C:\SomeDirectory\Test.txt"); would just return "Test.txt". You'll want to use the Path.GetDirectoryName to get the path of your input file, like so:
string inputDirectory = System.IO.Path.GetDirectoryName(args[i]);
Alternately, you can use the FileInfo class to retrieve a bunch more information about your input file. For example:
// Assuming args[i] = "C:\SomeDirectory\Test.txt"
FileInfo inputFile = new FileInfo(args[i]);
string inputDirectory = inputFile.DirectoryName; // "C:\SomeDirectory"
string inputFileName = inputFile.Name; // "Test.txt"
string fullInputFile = inputFile.FullName; // "C:\SomeDirectory\Test.txt"
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.