Files and Streams in ASP.NET
Richard Harris
DevOps, Online & Mobile at TD Bank Group #devops #agile #cloud #java #js #csharp
Overview
These notes explain how you can use the classes in .NET to read and change file system information and even build a simple file browser. You’ll also learn how to create simple text and binary files of your own. Finally, you’ll consider how you can allow users to upload their own files to your web server.?
Traditional file access is generally much less useful in a web application than it is in a desktop program. Databases, on the other hand, are designed from the ground up to support a large number of simultaneous users with speed, safety, and efficiency.?However, File access is so easy and straightforward in .NET that it may be perfect for simple, small-scale solutions that don’t need a full-fledged database product like SQL Server.
Contents
Tutorial
string guestBookName = Server.MapPath("~/App_Data/GuestBook");
Reference
System.IO Classes > Common Methods & Examples
Key System.IO Namespace Classes
Examples > Directory
// Retrieve the list (array) of files
string[] fileList = Directory.GetFiles(ftpDirectory);
// Get Parent Directory?
if (Directory.GetParent(strCurrentDir) != null)
{
// i.e. Browse 'Up One Level'
string newDir = Directory.GetParent(strCurrentDir).FullName;?
// ShowFilesIn(newDir);
// ShowDirectoriesIn(newDir);
}
Examples > File
// Display file information?
File.GetCreationTime(fileName);
File.GetLastAccessTime(fileName);
// File.Delete
File.Delete(fileName);
// FileAttributes - Access attribute information:?
FileAttributes attributes = File.GetAttributes(fileName);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) // or .Hidden
{
// This is a read-only file
}
// File.WriteAllLines() - Write the file in one shot
string[] lines = new string[]{"This is the first line of the file.",?
? "This is the second line of the file.",?
? "This is the third line of the file."};?
File.WriteAllLines(@"c:\testfile.txt", lines);
// File.ReadAllLines()?- Read the file in one shot?
string content = File.ReadAllLines(@"c:\testfile.txt");
?
Tip: You can use methods such as DirectoryInfo.GetFiles() and DirectoryInfo.GetDirectories() to create a simple file browser.?
Examples > DirectoryInfo
// Create a new directory:
DirectoryInfo myDirectory = new DirectoryInfo(@"c:\Temp\Test");?
myDirectory.Create();
DirectoryInfo dirInfo = new DirectoryInfo(dir);
// Show Files in Directory?
foreach (FileInfo fileItem in dirInfo.GetFiles())
{
FilesList.Add(fileItem.Name);
}
// Show Sub-Directories in Directory?
foreach (DirectoryInfo dirItem in dirInfo.GetDirectories())
{
DirectoryList.Add(dirItem.Name);
}
string guestBookData = Server.MapPath("~/App_Data/GuestBook");
DirectoryInfo guestBookDir = new DirectoryInfo(guestBookData);
foreach (FileInfo fileItem in guestBookDir.GetFiles())
{
// process fileItem (each file within ~/App_Data/GuestBook)
}
Tip: When putting data files in the App_Data folder, the web application ensures that the user can’t access any of the files directly, because the web server won’ t allow it.
Examples > File Info
// Create a new file:?
FileInfo myFile = new FileInfo(@"c:\Temp\Test\readme.txt");?
myFile.Create();
FileInfo = selectedFile = new FileInfo(fileName);
StringBuilder info = new StringBuilder();
info.Append("File: ");
info.Append(selectedFile.Name);
info.Append("| Size: ");
info.Append(selectedFile.Length);
info.Append("| Created: ");
info.Append(selectedFile.CreationTime.ToString());
info.Append("| Last Accessed: ");
info.Append(selectedFile.LastAccessTime.ToString());
Examples > Path
领英推荐
// Path.Combine?
// Fuse together the path of a folder with a sub-folder or file.?
string ftpDirectory = Path.Combine(Request.PhysicalApplicationPath,"FTP");
string newDir = Path.Combine(strCurrentDir, strSelectedDir);
string fileName = Path.Combine(strCurrentDir,strSelectedFile);
// Combine Application path with sub-folder path:
string absolutePath = @"c:\Users\MyDocuments";?
string subPath = @"Sarah\worksheet.xls";
string combined = Path.Combine(absolutePath, subPath);?
// Path.GetFileName
string fileName2 =
Path.GetFileName(@"c:\Documents\Upload\Users\JamesX\resume.doc");
// StreamWriter (designed for writing text files).?
StreamWriter w = File.CreateText(@"c:\myfile.txt");?// Create the file
w.WriteLine("This file generated by ASP.NET");? // Write a string
w.WriteLine(42);? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // Write a number
w.Close();?
FileInfo newFile = new FileInfo(@"c:\Temp\data.txt");?
StreamWriter w = newFile.CreateText();
// Write the information to the file.
w.WriteLine(DateTime.Now().ToString());
w.WriteLine(strMessage);
w.Flush();
w.Close();
// StreamReader?
StreamReader r = File.OpenText(@"c:\myfile.txt");?
string inputString;?
inputString = r.ReadLine();? ? // = "This file generated by ASP.NET"?
inputString = r.ReadLine();? ? // = "42"
// StreamReader - Entire File
StreamReader r = File.OpenText(@"c:\myfile.txt");?
string line;?
do?
{?
line = r.ReadLine();?
if (line != null)?
{?
// (Process the line here.)?
}?
} while (line != null);
r.Close();
// Parse Data from File?
FileInfo entryFile = new FileInfo(@"c:\Temp\data.txt");?
StreamReader r = entryFile.OpenText();
string Submitted = DateTime.Parse(r.ReadLine());
string Message = r.ReadLine();
r.Close();
Examples > FileStream
// FileStream & StreamReader - multiuser-friendly?
FileStream fs = File.Open(@"c:\myfile.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);?
StreamReader r = new StreamReader(fs);?
Examples > BinaryReader
// BinaryReader
BinaryReader r = new BinaryReader(File.OpenRead(@"c:\binaryfile.bin"));?
string str;?
int integer;?
str = r.ReadString();?
integer = r.ReadInt32();?
r.Close();?
// BinaryReader - multiuser-friendly?
FileStream fs = File.Open(@"c:\binaryfile.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);?
BinaryReader r = new BinaryReader(fs);
Examples > BinaryWriter
// BinaryWriter
FileStream fs = File.OpenWrite(@"c:\binaryfile.bin");?
BinaryWriter w = new BinaryWriter(fs);
string str = "ASP.NET Binary File Test";?
int integer = 42;?
w.Write(str);?
w.Write(integer);?
w.Close();?
Reference
Files and Web Applications
There are several limitations to files:
File Paths in Strings?
string myDirectory = "c:\\Temp\\MyFiles";
string myDirectory = @"c:\Temp\MyFiles";?
Tips
Reading and Writing with Streams
Text Files
Binary Files
The FileUpload Control
<asp:FileUpload ID="Uploader" runat="server" />?
Uploader.PostedFile.SaveAs(@"c:\Uploads\newfile");?
Examples > FileUpload Control
// To get information about the posted file content,?
// you can access the FileUpload.PostedFile object.?
// ASPX Controls:?
// Choose an image to upload: <br />
// <asp:FileUpload ID="Uploader" runat="server" /> ?
// <asp:Button ID="cmdUpload" runat="server" OnClick ="cmdUpload_Click" Text="Upload" /><br />
// <br />
// <asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True"></asp:Label>
protected void cmdUpload_Click(object sender, EventArgs e)
{
string uploadDirectory = Path.Combine(Request.PhysicalApplicationPath, "Uploads");
// Check that a file is actually being submitted.
if (Uploader.PostedFile.FileName == "")
{
lblInfo.Text = "No file specified.";
}
else
{
// Check the extension.
string extension = Path.GetExtension(Uploader.PostedFile.FileName);
switch (extension.ToLower())
{
case ".bmp":
case ".gif":
case ".jpg":
break;
default:
lblInfo.Text = "This file type is not allowed.";
return;
}
// Using this code, the saved file will retain its original
// file name, but be stored in the current server
// application directory.
string serverFileName = Path.GetFileName(Uploader.PostedFile.FileName);
string fullUploadPath = Path.Combine(uploadDirectory, serverFileName);
try
{
// This overwrites any existing file with the same name.
// Use File.Exists() to check first if this is a concern.
Uploader.PostedFile.SaveAs(fullUploadPath);
lblInfo.Text = "File " + serverFileName;
lblInfo.Text += " uploaded successfully to ";
lblInfo.Text += fullUploadPath;
}
catch (Exception err)
{
lblInfo.Text = err.Message;
}
}
}
The Maximum Size of a File Upload?
<?xml version="1.0" encoding="utf-8" ?>?
<configuration>?
? <system.web>?
<!-- Other settings omitted for clarity. -->?
<httpRuntime maxRequestLength="8192" />?
? </system.web>?
</configuration>?