Can't load file from path - c#

I have an problem loading an xml from a path, because on my pc(and others) part of the path is mapped:
This is the path i have from the database:
\serverName\files\System\Appldata\Application\3_5\TEST\Program\Version.xml
But on my computer the path looks like this:
Y:\Application\3_5\TEST\Program
This is the code:
var path = new DirectoryInfo(x.LocationName+#"\"+x.FolderName);
var doc = new XmlDocument();
//Loading the file
doc.Load(path.FullName + #"\Version.xml");
Are there any way around this problem?

Well, do not try to concatenate by yourself the path and the filename.
Use Path.Combine
doc.Load(Path.Combine(path.FullName, "Version.xml"));
This requires the using System.IO; at the beginning of your source file.
Of course you could use both the mapped version or the full sharename only if you have the permissions to you remote folder. Also, if your database keeps the full sharename be sure that it is stored with the two initial backslash
EDIT Seeing your edit now, again, do not manually build your paths (and check if the info are valid)
var path = new DirectoryInfo(Path.Combine(x.LocationName, x.FolderName));
if(!path.Exists)
{
MessageBox.Show("Invalid path retrieved:" + path.FullName);
return;
}
var doc = new XmlDocument();
doc.Load(Path.Combine(path.FullName,"Version.xml"));

You are accessing the file using network path. Please make sure that you are able to access the file from the file explorer on webserver.
Try this code:
var doc = new XmlDocument();
var finalPath = Path.Combine(x.LocationName, x.FolderName, "Version.xml");
//Loading the file
doc.Load(finalPath);

Related

How to create file text in "AppData\Roaming" for any user in C#

I'd like save date my app but I'm not knowing if app save for different users, Example if "andy" I can't use ("C:\Users\Game maker\AppData\Roaming") ,So How to create file in "AppData\Roaming\MaxrayStudyApp" for any user .
Computer myComputer = new Computer();
myComputer.FileSystem.WriteAllText(#"C:\Users\Game maker\AppData\Roaming\MaxrayStudy\data.txt","", false);
Almost a duplicate of this one: Environment.SpecialFolder.ApplicationData returns the wrong folder
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
That should get the folder you need then use Path.Combine() to write to a directory in that folder.
var roamingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(roamingDirectory, "MaxrayStudy\\data.txt");
I restart my windows and I write this
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
filePath= (filePath+#"\MaxrayStudyApp\data.txt");
string path =Convert.ToString(filePath);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(filePath,false)){
file.WriteLine(" XP : 0");}

how to verify if an input read from console is a file name or a file full path

I have a console application in C# and I would like to load an xml file, the path to the file is provided via console.readline(). But, I would like to load the file from the provided path but if the user only provides the name of the file I would like to search for it in the local folder from where the application is running. How can I know when I get only a file name as an input or a file full path.
I managed that using: var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
But this ugly and probably very buggy.
Full code:
var xmlFilePath = Console.ReadLine();
var xmlFile = new XmlDocument();
var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
try
{
if (isFileNameOnly)
{
xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFilePath);
}
xmlFile.Load(xmlFilePath);
}
Thx
You can check if the file name entered by user actually exists using Exists() method. If it returns true load the file.
File.Exists(xmlFilePath)
Also XmlDocument.Load() if provided only file name will try to find the file in the BaseDirectory itself. So if file.Exists() return true you can assume XmlDocument.Load will load it whether it is local or absolute path.
This will return false:
bool isFolder = Path.IsPathRooted(#"Text.txt");
This will return true:
bool isFolder = Path.IsPathRooted(#"C:\Text");
Your approach is the same that I would have chosen. If the param doesn't contain any directory delimiter char, then it must be a filename only. Maybe it would be a little more elegant if you did it like this:
bool isFileNameOnly = !xmlFilePath.Contains(Path.DirectorySeparatorChar.ToString());

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

c# .dat file assign to variable

how can i assign a to a variable, which is located at the same project, for example at my project i created a folder named App_Data and for example the file is file.dat , how can i assign the file at a variable,.. for example:
var file = App_Data/file.dat
I need it to be assigned to a variable because i will be using that variable as a parameter to a method,.. it used to be :
var file= HttpContext.Current.Request.MapPath("/App_Data/file.dat");
but now i want the path to be at the same project
if it should be absolute path it should be fine too
The MapPath should give you the absolute location of the file on disk from a relative url to the root of your website:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
This should return something like:
c:\inetpub\wwwroot\MyWebSite\App_Data\file.dat
UPDATE:
It looks like you are trying to retrieve the contents of the file, not the location. Here's how this could be done:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
string fileContents = System.IO.File.ReadAllText(absoluteFileLocation);
You need to read the file using one of the available methods (Streams, Readers, etc).
The easiest would be:
string fileContent = File.ReadAllText(fileNameAndPath);
where the variable fileNameAndPath contains the full path and file name to the file as described by Darin Dimitrov.
Your intention isn't exactly clear, anyway:
if you want file stats:
System.IO.File file = new System.IO.File("~/App_Data/file.dat");
if you want the file content use:
public static string readFileContent(String filename)
{
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
return sr.ReadToEnd();
}
catch { return String.Empty; }
}

Visual studio cannot locate XML file

I'm attempting to develop a Windows 7 Phone and I am using an XML file that I need to parse and then perform a Linq query on.
The problem is this:
Whenever I try to access the file (it is stored locally) it brings back an error saying the file cannot be found as it's not part of the XAP package.
I have tried another solution where I use StreamReader But I am still getting a simular error:
Attempt to access the method failed System.IO.File.OpenText(System.String)
Here is the code that I am using:
using (StreamReader reader = File.OpenText("C:/Users/Desktop/Assign/obj/Debug/buildings.kml"))
{
var xdoc = XDocument.Load ("buildings.kml");
XNamespace kml = "http://www.opengis.net/kml/2.2";
var dict = xdoc.Descendants(kml + "Placemark")
.ToDictionary(d => d.Element(kml + "name").Value,
d => d.Element(kml + "id").Value);
foreach (var b in dict) {
Console.WriteLine ("Building Name -> " + b.Key + " Building ID -> " + b.Value);
}
}
The file is located in: > C:/Users/Desktop/Assign/obj/Debug/buildings.kml so I cannot see the problem. Outside of Visual Studio, I can read in the .xml file fine.
Hope someone can help
EDIT:
New code -
Dictionary<string, string> getBuildingNames()
{
Uri uri = new Uri(#"Data\mydata.kml", UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(uri);
StreamReader sr = new StreamReader(sri.Stream);
var xdoc = XDocument.Load(sr);
XNamespace kml = "http://www.opengis.net/kml/2.2";
var dict = xdoc.Descendants(kml + "Placemark")
.ToDictionary(d => d.Element(kml + "name").Value,
d => d.Element(kml + "id").Value);
return dict;
}
Error: - 'NullReferenceException was unhanded'
Assuming you really are trying to do this as part of a WP7 project (rather than some non-mobile project related to it, e.g. preprocessing) you shouldn't be using File.OpenText.
Options:
Include the XML in your XAP file, and read from that using Application.GetResourceStream (see this blog post for details)
Somehow get the XML into isolated storage, and use the isolated storage API
Embed the resource into your assembly, and use Assembly.GetManifestResourceStream.
Just a couple of some more tips to help you along:
1) Change the Build action property of the xml file to "Content". (Select the file and go to the properties window in Visual Studio)
2) If you only want to read from the file, then there is no need to have the file in IsolatedStorage. You can simply read it if you correctly set the Build Action property.
You can use XDocument to read the file.
XDocument xdoc = XDocument.Load(filepath);
where filepath is simply the relative path to the XML file, i.e. if you did not place it inside any folder in your project then it will be just the file name (assume it like being the root directory)

Categories

Resources