15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

792 ❘ ChaPTer 29 mAnipulAtinG files And the reGistry<br />

Next, you add a couple of fields to the main form class — one representing the file dialog <strong>and</strong> a string that<br />

gives the path of the file currently being viewed:<br />

partial class Form1: Form<br />

{<br />

private readonly OpenFileDialog chooseOpenFileDialog =<br />

new OpenFileDialog();<br />

private string chosenFile;<br />

code download BinaryFileReader.sln<br />

You also need to add some st<strong>and</strong>ard Windows Forms code to deal with the h<strong>and</strong>lers for the menu <strong>and</strong> the<br />

file dialog:<br />

public Form1()<br />

{<br />

InitializeComponent();<br />

menuFileOpen.Click += OnFileOpen;<br />

chooseOpenFileDialog.FileOk += OnOpenFileDialogOK;<br />

}<br />

void OnFileOpen(object Sender, EventArgs e)<br />

{<br />

chooseOpenFileDialog.ShowDialog();<br />

}<br />

void OnOpenFileDialogOK(object Sender, CancelEventArgs e)<br />

{<br />

chosenFile = chooseOpenFileDialog.FileName;<br />

this.Text = Path.GetFileName(chosenFile);<br />

DisplayFile();<br />

}<br />

code download BinaryFileReader.sln<br />

As this code demonstrates, when the user clicks OK to select a file in the file dialog, you call the<br />

DisplayFile() method, which does the work of reading in the selected file:<br />

void DisplayFile()<br />

{<br />

int nCols = 16;<br />

FileStream inStream = new FileStream(chosenFile, FileMode.Open,<br />

FileAccess.Read);<br />

long nBytesToRead = inStream.Length;<br />

if (nBytesToRead > 65536/4)<br />

nBytesToRead = 65536/4;<br />

int nLines = (int)(nBytesToRead/nCols) + 1;<br />

string [] lines = new string[nLines];<br />

int nBytesRead = 0;<br />

for (int i=0; i

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

Saved successfully!

Ooh no, something went wrong!