Path to read file from inside www folder - c#

I have a binary reader to read a file
BinaryWriter bw2 = new BinaryWriter(File.Open(#"c:\test\test6.xml", FileMode.OpenOrCreate));
the path i have set to is c:\test\test.xml
However it needs to read the file from www folder hosted site
so www\test\test.xml
should it be ~\test\test.xml?
Not sure.
Thanks for your help

Check out Server.MapPath() http://msdn.microsoft.com/en-us/library/ms524632(v=VS.90).aspx
So in your case, you're after this:
using (BinaryWriter bw2 = new BinaryWriter(File.Open(Server.MapPath(#"~\test\test6.xml", FileMode.OpenOrCreate)))
{
...
}
Notice I added the using() which is a best-practice for working with expensive resources like files.
Of course, you really should seperate out file opening from object creation so you can have better diagnostics in your code.

Probably you need this function: http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

Related

Receiving IOException

I'm getting the IOException Error when I try this, and I'm not sure what I'm doing wrong:
This is my code:
FileStream fStream = new FileStream(PDFFilePath(), FileMode.CreateNew, FileAccess.ReadWrite);
Where
private string PDFFilePath()
{
m_sFilePath = "C:/Pictures/";
return m_sFilePath;
}
What am I missing?
I'm using this FileStream to save PDF documents using the Pdf.Select NuGet. It uses a method:
PdfDocument.Save(Stream stream);
I think you should be specifying your path this way:
private string PDFFilePath(string filename)
{
m_sFilePath = #"C:\Pictures\" + filename;
return m_sFilePath;
}
Like #Reisclef said, you have to provide a file path, not a directory. Since you're using FileMode.CreateNew, it has to be a new file, so you might also want to use File.Exists(m_sFilePath) before returning.
You have several problems here.
First, if you use a path like C:\Pictures\, it'll complain about the trailing \.
Secondly, you need to specify an actual file here, not just a directory. It makes no sense to just specify a directory (rather than a file) in this case - that's why it's called a File Stream and not a Directory Stream. I suggest using Path.Combine for this. Also, if you're just trying to move an already-existing file to this directory, you should do File.Move rather than using a FileStream.
Third, you only want to use FileMode.CreateNew if there's no possibility that the file already exists in the destination folder; if it does exist, this will throw an exception.
Fourth, it's a bad practice to hardcode paths like this. You usually want to get the path from a configuration file and make sure that the Pictures directory does, in fact, exist before you try to do this operation; otherwise it may fail when you deploy it to another machine.
Fifth, the PDFFilePath method seems rather pointless in this case - you can do the same thing with a string constant or creating a readonly string in the constructor.

How can I open a text file relative to my MVC project?

In my bin file I have set up som test data, and I want my application to be able to access logfiles that are stored in bin/log/log00001.txt.
However, in my crontroller, when I try to use a TextReader on the following path it goes somewhere else: new StreamReader("log/log00001.txt")
How do I read stuff relative to my project?
Try using
StreamReader reader = new StreamReader(Server.MapPath("~/bin/log/log00001.txt"));
HttpContext.Current.Server.MapPath("~/some/path/relative/to/your/web/app")

Regarding StreamReader

Why is this not working ?
StreamReader m = new StreamReader("../folder1/email.html", System.Text.Encoding.UTF8);
code file and html file are in diff folders so I that its some path issue but its not because I just now copied this html file in the same folder where this code file is and changed code to:
StreamReader m = new StreamReader("email.html", System.Text.Encoding.UTF8);
still not working.. What's wrong? Is the syntax wrong or what?
If you use a relative path it will be relative to the bin/Debug or bin/Release folder, not the project folder where your code file is, so try:
m= new StreamReader("../../email.html", System.Text.Encoding.UTF8);
You say that there's no exception with your code. This means that the file is successfully opened for reading. I suspect that you are not reading anything from this StreamReader, you are simply instantiating it and probably not releasing.
Make sure you dispose this stream or you might leak handles. If all you need to do is read the file contents you could use the ReadAllText method:
string contents = File.ReadAllText("email.html");
If the file is not found you will get an exception.
You are probably not reading it ...try this ...put the file in your Bin/Debug directory and...
StreamReader m = new StreamReader("email.html", System.Text.Encoding.UTF8);
Console.Write(m.ReadToEnd());
Console.ReadLine();

How can I create a file with StreamWriter using a relative path?

When I run the following code, an XML file is correctly created in c:\temp:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Models.Customer>));
using (StreamWriter wr = new StreamWriter("C:/temp/CustomerMock2.xml"))
{
xs.Serialize(wr, CustomerList);
}
However, I actually want it to be created in a sub-directory underneath the project, but when I do this:
using (StreamWriter wr = new StreamWriter("Data/CustomerMock2.xml"))
it just acts as if it writes it but the file never appears in that directory:
C:\Projects\Prototype12\CustomersModul\bin\Debug\Data.
How can I create a file with StreamWriter with a relative path inside my project?
It is always dangerous to rely on the 'Current Directory' concept, so you will need a starting point. In a WinForms project, you can get the location of the .EXE with
string exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
In WPF there will be something similar.
But if you are in a library and do not have access to the Application (or Environment) objects, you should consider making a BaseFolder parameter or property to let the main application take control over folders.
Does ./Data/CustomerMock2.xml work?
using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))
Are you setting the XML data to be copied at compile time (so it's not in the actual project directory, but the bin folder)? In which case you can get to it using
string xmlFile = string.Format("{0}/Data/{1}",AppDomain.CurrentDomain.BaseDirectory,"myxml.xml");
Relative paths are relative to the current directory. Maybe you're not in the bin/debug directory... You should build the absolute path based on the exe directory, as shown by Chris.
Also, the StreamWriter constructor won't create the directory, you need to create it explicitly if it doesn't exist.

Creating and saving a text file to the server

In C# ASP.Net, I would like to create and save a text file to a server. This will be happening daily (by a user action, not scheduled).
I would like the location to not be in the application path but in a separate folder (for this question, lets say the folder is off the root).
I am new to this site and if this question is too "open", feel free to let me know.
Thanks for your assistance.
I agree with Dan Herbert. Put the path in web.config and make sure the permissions for the folder are correct.
Also, make sure that path is not on the C drive. That way, if something goes wrong, or if the site is attacked, the c drive won't fill up and crash the server.
Be careful with the permissions; even a simple text file can be dangerous if a hacker can muck with the path somehow. Think about someone overwriting the server's hosts file, for example.
One good practice to follow is to use a web.config app setting key to define the output path of your application.
You'd use the ConfigurationManager.AppSettings class for retrieving values from a web.config. You can read how to do this here:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx
Here is an example:
// Pass a path and filename to the StreamWriter's
// constructor. The path must already exist but the
// file will be created if it does not already exist.
using (TextWriter tw = new StreamWriter("c:\\foo\\bar.txt"))
{
tw.WriteLine("hello world");
}
You can use System.IO classes to save to a file on the local filesystem.
using(var w = new StreamWriter(filename))
{
w.WriteLine("Hello world!");
}
Just to add on what others have said, when writing to a file in a multi-threaded application, you need to synchronize the access to this resource. You could use ReaderWriterLockSlim to achieve this:
// Make this a static field
ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
_lock.EnterWriteLock();
try
{
File.WriteAllText(#"c:\test.txt", "some info to write");
}
finally
{
_lock.ExitWriteLock();
}
I don't see any specific issue in doing so. You just need to make sure the user running ASP.NET is granted the required permissions to write to the output folder.
You'll want to use Server.MapPath to get to the physical path of your folder.
using (TextWriter tw = new StreamWriter(Server.MapPath("Folder1")))
{
tw.WriteLine("hello world");
}

Categories

Resources