13.07.2015 Views

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 15: Files 375Ask the ExpertQ: Wouldn’t it be easier to use a word processor to save files? Then when they’reloaded using <strong>ASP</strong>.<strong>NET</strong> <strong>3.5</strong>, all of the formatting is preserved.A: I agree that it would be great if a client could update material on a web site simplyby changing the contents of a word processor file. However, word processor filesare binary files containing a lot of code that formats the text. Text files are typicallyUnicode, and most use the UTF-8 encoding and can be written and read using the textmethods in <strong>ASP</strong>.<strong>NET</strong> <strong>3.5</strong> and C# 3.0. Older text files use the ASCII format, but becauseUnicode is backwardly <strong>com</strong>patible with ASCII, they too can be read. Any formatting ofthe text is ac<strong>com</strong>plished by treating the file as a string, and by parsing the string, youcan dynamically format the text. However, that’s not quite as easy as having the abilityto bring in a wholly formatted word-processed file.A crucial feature in specifying the path is the use of the @ symbol. If it is not used, thebackslashes (\) are assumed to be part of an escape sequence, and this generally causes anerror. An alternative to using the @ symbol is to use MapPath. The next section showshow and why it is probably a better choice in general.Using MapPathIn the previous example using the @ symbol, the exact path needs to be listed. That worksout fine for files on your own system, but when you’re working on a remote server, youmay not know the exact path. Using the MapPath method, you can map a specifiedvirtual path to a physical path. If you do not know the exact path, simply enter the name ofthe text file you wish to create, and it is created in your root directory with the <strong>ASP</strong>X andCS files of your web site. The format isusing(StreamWriter swInstance = new StreamWriter MapPath("Mapped.txt"))){ ….}As you can see, MapPath is used in setting up a StreamWriter operation. The followinglistings show how to use the MapPath method in an application:<strong>ASP</strong>.<strong>NET</strong> MapFile.aspx

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!