INT422 Internet III Web Programming on Windows - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

INT422 Internet III Web Programming on Windows

Description:

All File I/O operations in .NET are done using classes found in the System.IO namespace ... FileNotFoundException IOException. Catch(FileNotFoundException fnfEx) ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 34
Provided by: team61
Category:

less

Transcript and Presenter's Notes

Title: INT422 Internet III Web Programming on Windows


1
INT422 Internet III Web Programming on
Windows
  • File I/O to and from the web server

2
System.IO Namespace
  • All File I/O operations in .NET are done using
    classes found in the System.IO namespace
  • using System.IO
  • There are 5 main File I/O classes
  • Directory
  • File
  • Path
  • DirectoryInfo
  • FileInfo

3
Static Classes vs. Instance Objects
  • Recall that Static classes, methods, properties,
    etc. belong to the CLASS and not to a particular
    object.
  • In other words, you dont need to make a New
    object based on the class in order to use its
    methods
  • Directory, File, Path Static
  • File.Copy(c\temp\myfile.txt, c\docs)
  • DirectoryInfo, FileInfo Instance
  • FileInfo fi New FileInfo(c\temp\myfile.txt)
  • fi.CopyTo(c\docs) //Note No Source fi is
    the source

4
System.IO.Directory - Highlights
  • Delete(path, recursive)
  • Move(source, dest) Used for Rename too
  • Exists(path) -gt returns Boolean
  • GetParent(path) -gt returns DirectoryInfo
  • GetDirectoryRoot(path) -gt returns String
  • CreateDirectory(path) -gt returns DirectoryInfo
  • GetFiles(path) -gt returns String()
  • GetDirectories(path) -gt returns String()
  • GetFileSystemEntries(path) -gt returns String()

5
System.IO.File - Highlights
  • Used to work with Closed files. If you want to
    open a file and work with it, you need a FileInfo
    object instead
  • Delete(path)
  • Move(source, dest) Used for Rename too
  • Exists(path) -gt returns Boolean
  • Copy(source, dest, overwrite)

6
System.IO.Path - Highlights
  • Static methods and properties for working with
    file system Paths
  • string tempPath Path.GetTempPath()
  • // Side effect creates the temp file
  • string tempFile Path.GetTempFileName()
  • string p "c\temp\mydocs\readme.txt
  • string info
  • info Path.GetDirectoryName(p) //
    c\temp\mydocs
  • info Path.GetFileName(p) // readme.txt
  • info Path.GetExtension(p) // .txt
  • info Path.GetFileNameWithoutExtension(p) //
    readme
  • info Path.Combine(Path.GetDirectoryName(p),
    "data.txt")
  • // c\temp\mydocs\data.txt

7
System.IO.DirectoryInfo - Highlights
  • Represents an actual Directory, and then allows
    you to enumerate (i.e., loop across) its contents
  • DirectoryInfo di new DirectoryInfo(".\temp")
  • string n di.Name // temp
  • string fn di.FullName // C\temp
  • DirectoryInfo subDir di.CreateSubdirectory("a")
  • fn subDir.FullName / C\Temp\a
  • foreach(FileInfo txtFile In di.GetFiles(".txt"))
  • // Do something with Text File
  • subDir.Delete()

8
System.IO.FileInfo Highlights
  • Represents an actual File
  • FileInfo fi New FileInfo("c\temp\a.txt")
  • DirectoryInfo di New DirectoryInfo("c\temp")
  • string n fi.Name // a.txt
  • string fn fi.FullName // C\temp\a.txt
  • DirectoryInfo subDir di.CreateSubdirectory("a")
  • long l fi.Length // Size in bytes
  • string pdir fi.DirectoryName // temp
  • fi.CopyTo("c\documents")

9
Reading and Writing Files
  • Streams
  • StreamReader
  • StreamWriter

10
The Stream Class
  • .NET I/O uses Streams to Read and Write data
  • A Stream represents a sequence of bytes going or
    coming from a storage medium (e.g., a file)
  • Streams are low-level objects that work at the
    Byte level. Most Streams allow the following
  • Read Read a specified number of bytes
  • Write Write a specified number of bytes

11
The Stream Class continued
  • Stream is an Abstract Class, which means you
    cant create a new Stream object
  • Instead, you use classes that Inherit from
    Stream
  • FileStream - This is what we need for File I/O
  • MemoryStream - Use RAM like a File (very fast)
  • NetworkStream - Used for network communication
  • Data in a Stream is Buffered transparently, and
    only written to the storage medium when Flushed
    or when the Stream is closed.

12
StreamReader and StreamWriter
  • Normally you dont work with a Stream directly
  • Most of the time we need to Read or Write lines
    of text, Integers, Doubles, etc.
  • Streams only understand Bytes (data type)
  • To make things easier we use a StreamReader or
    StreamWriter, which sits on top of a Stream and
    converts our data into / from Bytes.

13
The Complete IO Picture Reading
File
.NET App
StreamBuffer
FileStream
StreamReader
  • StreamReader sr1 File.OpenText(a.txt)
  • OR
  • FileInfo fi new FileInfo(a.txt)
  • StreamReader sr2 fi.OpenText()
  • OR
  • StreamReader sr3 New StreamReader(a.txt)

14
Reading Text From a StreamReader
  • If the file is small (lt50 KB), consider reading
    the whole thing at once. Otherwise, go into a
    loop
  • string entireFile sr1.ReadToEnd()
  • sr1.Close()
  • OR
  • string oneLine
  • while(sr1.Peek ! -1)
  • oneLine sr1.ReadLine() // sr1.Read gives 1
    letter
  • // Process onLine here
  • sr1.Close()

15
The Complete IO Picture - Writing
File
.NET App
StreamBuffer
FileStream
StreamWriter
  • StreamWriter sw1 File.CreateText(a.txt)
  • OR
  • StreamWriter sw2 New StreamWriter(a.txt)
  • OR
  • string tempFile Path.GetTempFileName()
  • StreamWriter sw3 New StreamWriter(File.Open(temp
    File, FileMode.Open))

16
Writing Text with a StreamWriter
  • If you have a string which includes NewLine
    characters, you just write the whole thing at
    once and the NewLines will be preserved. If you
    want to add NewLines, you have do it manually.
  • string someText Im going to disk
  • sw1.WriteLine(someText) // Adds NewLine to end
  • sw1.Close()
  • OR
  • sw1.Write(txtUserInput.Text) // No NewLine at
    end
  • sw1.Close()

17
Writing Textcont
  • Writing a file for the Web? For Unix? Change the
    NewLine character used by StreamWriter
  • string line1 This is line 1
  • string line2 This is line 2
  • sw.NewLine ltbr /gt// Assume sw has been
    declared
  • sw.WriteLine(line1) // Adds ltbr /gt to end
  • sw.WriteLine(line2) // Adds ltbr /gt to end
  • sw.Close()
  • OR
  • sw.NewLine ControlChars.LF // For Unix EOL
  • sw.WriteLine(line1) // Adds LF to end (not CRLF)
  • sw.Close()

18
Another StreamReader StringReader
  • While were discussing StreamReaders, you should
    also be aware of StringReader.
  • Imagine you want to read a very long String Line
    by Line (e.g., a Textbox control)
  • string oneLine
  • StringReader strR New StringReader(txtInput.Text)
  • while( strR.Peek ! -1)
  • oneLine strR.ReadLine() // Removes NewLine
  • // Process oneLine here

19
Working with Files on a Server
  • File System Paths
  • Virtual Paths
  • Dealing with Errors
  • Permissions

20
Understanding Server Paths
  • When you work on a Web Server, you deal with
    three types of paths
  • Virtual Path
  • http//warp.senecac.on.ca/int422_xxx/MyDirectory/
  • Actual File System Path
  • D\students\int422_xxx\webcontent\MyDirectory
  • Absolute path from your web forms
  • /MyDirectory
  • If you want to work with first two types on the
    server, you have to convert / map between them

21
Mapping Virtual to Actual Paths
  • Its easy to map between these two, using the
    Server.MapPath(path) method
  • string appPath Server.MapPath( _
  • http//warp.senecac.on.ca/jsmith/MyWebApp/)
  • If you pass a null path (e.g., Nothing), MapPath
    returns the fully rooted (i.e., absolute) file
    system path to the current directory
  • string appPath Server.MapPath(Nothing)

22
Working with Server Files
  • Imagine a Web App called
  • TextApp with this File Structure
  • How would you
  • Get the Path to Sample1.txt?
  • Read the contents of the file?
  • Display it in a Label Web Control?
  • Hint Assume that your ASP.NET web form is in the
    root of the TextApp directory, and that Docs is a
    sub-directory under TextApp

23
One Possible Answer
  • Get the path to Sample1.txt
  • string p Path.Combine(Server.MapPath(Nothing),
    _
  • \docs\samples\sample1.txt)
  • Open Sample1.txt for Reading
  • StreamReader sr New StreamReader(p)
  • Read the entire File into a Label
  • lblSampleText.Text sr.ReadToEnd()
  • Close the Sample1.txt file
  • sr.Close()

24
Things Can (and Do) Go Wrong
  • Any time you work with Static resources (e.g.,
    files, directories) errors can occur
  • Try to Open a file the OS is currently reading or
    writing, and youll get an error
  • Try to Move a file that isnt there, youll get
    an error
  • Try to use a Directory which you dont have
    rights to, youll get an error.

25
Recover From I/O Errors
  • Any I/O action that can cause an error should be
    placed in a trycatch block
  • This is called Structured Exception Handling.
    When an error occurs, an Exception Object will be
    Thrown, which you have to Catch and deal
    with, otherwise the user gets an error
  • try
  • File.Delete(txtFilename.Text)
  • lblResult.Text "File Deleted
  • catch // Any Generic Exception
  • lblresult.Text "Could not Delete File

26
Catching Specific Exceptions
  • There are lots of different Exceptions that get
    thrown, and Exception is just a generic Base
    Class for all of them. I/O specific Exceptions
  • DirectoryNotFoundException
  • FileLoadException PathTooLongException
  • FileNotFoundException IOException
  • Catch(FileNotFoundException fnfEx)
  • lblResult.Text Couldnt Find the File
  • Catch(DirectoryNotFoundException dnfEx)
  • lblResult.Text No such Directory

27
ASP.NET File I/O and Security
  • Question When your Web Apps I/O code runs,
    which users Security Context is it running in?
  • IUSR_warp
  • jsmith (or whatever user owns the application)
  • ASPNET
  • NETWORK SERVICE
  • Account of User Logged-into the Web Application
  • Something else???

28
Operating system dependent
  • Answer It depends upon the operating system
  • Warp runs Windows Server 2003, and IIS 6
  • The account is NETWORK SERVICE
  • Your Windows XP or Windows 2000 Server computer
    uses IIS 5.x
  • The account is ASPNET
  • This is the ASP.NET worker process account

29
File I/O and Securitymore
  • Why is this important? Whatever NTFS rights this
    user has, so will your program. Therefore,
    depending on who runs your code it may not have
    sufficient rights.

30
File I/O and Securitymore
  • Note
  • If you are using Anonymous or Forms based
    Authentication (most of our INT422 work), it is
    NETWORK SERVICE (or ASPNET if you are on your
    WXP/W2K PC)
  • If you are using Windows Based authentication, it
    will be the Account of the User Logged-into your
    Web App

31
Read OK Write?
  • The worker process account has read access to
    files in the web server virtual directories
  • It does NOT have write access by default
  • On the following pages, you will learn what you
    need to know about doing file I/O on warp and on
    a home PC

32
warp configuration
  • Every INT422 student already has a folder beside
    their website that can be used for file I/O
  • This folder is called data
  • Data is not accessible through URL because it is
    not in your website root (this minimizes security
    risks for hacking the website through web server)
  • The absolute path to this folder
    is_at_c\inetpub\int422_xxxxx\data
  • Use this data folder for file I/O

33
Home PC configuration
  • Use My Computer or Windows Explorer to locate
    your web app in the file system
  • It is probably under C\inetpub\wwwroot
  • Create a data folder beside wwwroot_at_c\inetpu
    b\data
  • Change its permissions to allow Modify for the
    ASPNET user.
Write a Comment
User Comments (0)
About PowerShow.com