Cannot read XML file with ReadXml Dataset Method - c#

I have the following method:
public static DataSet BringProducts()
{
DataSet dataSet = new DataSet();
var dir = #"ProductsCookieData.xml";
if (File.Exists(dir)) //without File.Exists, same problem.
{
dataSet.ReadXml(dir);
}
return dataSet;
}
The file exists but the method does not see it ever. The file is in C:\, I tried in other locations and the same happens. Also tried without using static.
If I don't use the File.Exists(), FileNotFoundException is throwing.

With the way you declared the file
var dir = #"ProductsCookieData.xml";
Your file has to be in the same directory as your code/current webpage and not in C:. You can give permission to C:\ and change your code to
var dir = #"C:\ProductsCookieData.xml";
Sometimes, the file can be copied to your application folder, root or special folder and accessed with Server.MapPath
var dir = Server.MapPath("~/ProductsCookieData.xml");

You need to specify the full path to the file. Currently, you're only providing a relative path, which will be resolved relative to the current working directory.
If your file is in the root of C:\, then change your code to:
string dir = #"C:\ProductsCookieData.xml";

Related

Read an xml file from non-web project in C# (Visual Studio)

I am trying to read an xml file that is present in one of the projects in my VS solution. Here's my code.
string path = HttpContext.Current.Server.MapPath(#"~\Resources\XmlDocument.xml");
XDocument document = XDocument.Load(path);
This works fine if my xml file is in the web project. But in reality I have my xml file in a different project under the same solution.
I cannot use Server.MapPath as this searches web project. I searched for an answer but did not find any solution that worked for me.
How can I access this xml file? I am trying to access this from a helper method in the same project.
Try this:
string path = HostingEnvironment.ApplicationPhysicalPath + (some path);
public void LoadXML()
{
if (System.IO.File.Exists(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<int>));
lock (new object())
{
using (TextReader reader = new StreamReader(path))
{
return (List<int>)(serializer.Deserialize(reader));
}
}
}
}
this is working for me.
Once you get your current directory, why not just navigate up a number of parent directories and then locate your file?
DirectoryInfo info = new DirectoryInfo(Environment.CurrentDirectory);
DirectoryInfo parent = info.Parent.Parent;
string file = Path.Combine(parent.FullName, #"your\path");
Here I use Environment.CurrentDirectory to get where the program is at now, but you can stack as many Parent elements as you need. Then you can combine the path to get to your file in the other project.
EDIT:
Once your application is running all the environment variables and Server.MapPath will give you the location that it is executing from (i.e. the path you are getting now). In light of this it may be easier to create a folder and reference this via it's full path. (C:\Data\myfile.xml)

In c#, how to copy a file without extension?

I've got a file named test_file which is a file without extension, the path is 'C:\share\'. And I want to copy it to a new folder so the code is:
File.copy(#"C:\share\test_file", #"C:\share\newFolder\test_file", true);
And it will throw an exception:
DirectoryNotFoundException: Could not find a part of the path C:\share\newFolder\test_file
Does anyone know how to solve this?
Do following
//get name of directory where you are copying the file to
var dir = Path.GetDirectoryName(#"C:\share\newFolder\test_file");
//create directory (following command will create all the missing folders in path)
Directory.CreateDirectory(dir);
File.Copy(#"C:\share\test_file", #"C:\share\newFolder\test_file", true);
Does newFolder exist? I'm guessing it doesn't. You need to create that folder, for example, using Directory.CreateDirectory it will create all necessary folders among given path. So it would be like:
Directory.CreateDirectory("C:\\share\newFolder\\");
and then
File.Copy(#"C:\share\test_file", #"C:\share\newFolder\test_file", true);

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

DirectoryNotFound Exception in C#

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}

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