System.IO Namespace

advertisement
System.IO Namespace
Imports System.IO
∆ίνει την δυνατότητα να δουλέψεις µε αρχεία και δεδοµένα:
DriveInfo,Directory,DirectoryInfo,File,FileInfo,FileSystemObject
FileStream
Path
StreamReader/StreamWriter
Controls
• OpenFileDialog
• SaveFileDialog
• FolderBrowserDialog
Ολα τα Dialog Control έχουν την µέθοδο ShowDialog()
Επιλογή Αρχείου- OpenFileDialog
Βάζοντας πάνω στην φόρµα ένα OpenFileDialog control και καλώντας την
OpenFileDialog1.ShowDialog() ,
θα εµφανιστεί το παραπάνω παράθυρο, στο οποίο διακρίνονται δυο βασικές ιδιότητες το Filename και
το φίλτρο επιλογής τύπου αρχείου (Filter).
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
MsgBox(“File name given:” + OpenFileDialog1.Filename )
End If
Τo Filename property περιέχει όλο το path.
Η απάντηση στον διάλογο µπορεί νάναι της µορφής π.χ. Windows.Forms.DialogResult.OK
[1]
Filter Property - Φίλτρο
Σε ζεύγη (περιγραφή | pattern), που µεταξύ τους χωρίζονται µε | π.χ.
“Text files (*.txt) | *.txt | All files (*.*) | *.*”
"Databases files (*.mdb;*.mda;*.mde)|*.mdb;*.mda;*.mde"
multiple pattern µε ;
OpenFileDialog1.Filter = "Text files (*.txt) | *.txt | All files (*.*) | *.*"
OpenFileDialog1.FileName = ""
Πολλές άλλες Properties..
Set InitialDirectory, RestoreDirectory.
Εvents
FileOK event
HelpRequest event
1.Ανάγνωση Αρχείου
(
My.Computer.FileSystem
sr = New StreamReader(filename)
File.OpenText
My.Computer.FileSystem.OpenTextFileReader)
Ανάγνωση αρχείου κειµένου
Υπάρχουν διάφοροι τρόποι για ανάγνωση αρχείου, οι δύο πιο γνωστοί είναι µε την χρήση
• του My Namespace και του component My.Computer.FileSystem (µε µεθόδους
ανάγνωσης ReadAllBytes και ReadAllText).
• της κλάσης StreamReader (µε µεθόδους ανάγνωσης Read, ReadLine και
ReadToEnd) .
My.Computer.FileSystem component /
ReadAllText
Ολο τo κείµενο του επιλεχθέντος αρχείου µπορεί να αναγνωστεί (µε µιας) και να επιστραφεί
σε ένα String που µπορεί να αντιγραφεί π.χ. µέσα σε ένα textbox control
(µε ιδιότητες ScrollBars=Both, Multiline=True), όπως πιο κάτω:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Button1.Click
Dim s As String
[2]
If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
Try
s = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
TextBox1.Text = s
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
End Sub
(∆ιαβάζοντας ένα text αρχείο µε το Μy.Computer.FileSystem.ReadAllText και ΟpenFileDialog )
The ReadAllText method copies the entire contents of the specified text file to a string
variable or object (in this case, a string variable named s), so in terms of performance and
coding time, ReadAllText is faster than reading the file one line at a time (όπως µε την
ReadLine του StreamReader βλέπε πιο κάτω)
(ReadAllText -> Insert Snippet / Fundamentals – Collections, Data Types, File System, Math /
File System –
Processing Drives, Folders, And Files / Read Text From A File )
The StreamReader Class /
ReadΤοEnd
ReadLine
Imports System.IO
Μέθοδοι ανάγνωσης Read, ReadLine, ReadToEnd(), διαβάζει το stream και το επιστρέφει σε µια µεταβλητή
String.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Dim sr As StreamReader
If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
sr = New StreamReader(OpenFileDialog1.FileName)
'sr=File.OpenText(OpenFileDialog1.FileName)
Try
'Reads the stream from the current position to the end of the stream.
TextBox3.Text = sr.ReadToEnd()
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
sr.Close()
End If
End Sub
(∆ιαβάζοντας ένα text αρχείο µε StreamReader1.ReadToEnd και ΟpenFileDialog )
•
You can also use a combination of the My namespace and the StreamReader class.
Dim sr As StreamReader
Dim AllText, LineOfText As String
sr =My.Computer.FileSystem.OpenTextFileReader(OpenFileDialog1.FileName)
'sr = File.OpenText(OpenFileDialog1.FileName)
Do Until sr.EndOfStream 'read lines from file
LineOfText = sr.ReadLine()
'add each line to the AllText variable
AllText = AllText & LineOfText & vbCrLf
Loop
[3]
TextBox1.Text = AllText 'display file
sr.Close()
(∆ιαβάζοντας ένα text αρχείο µε StreamReader1.ReadLine και ΟpenFileDialog και ΜyNamespace)
•
Mπορείτε να χρησιµοποιήσετε το OpenFileDialog control µε την συνάρτηση
FileOpen (αριθµός αρχείου, διαδροµή, κατάσταση) - αριθµός 1..255- και τα
LineInput, EOF και FileClose
Dim All As String =””, Line As String=””
FieOpen(1,OpenFileDialog1.FileName,OpenMode.Input)
Do Until EOF(1)
Line= LineInput(1)
All = All & Line & vbCrlf
Loop
FileClose(1)
(∆ιαβάζοντας ένα text αρχείο µε FileOpen και ΟpenFileDialog )
•
µπορείτε επίσης να χρησιµοποιήσετε το OpenFileDialog control µε την συνάρτηση
PrintLine
•
Tέλος µπορείτε και να διαβάσετε ένα υπάρχον text αρχείο σας χωρίς χρήση
διαλόγου OpenFileDialog:
Dim lfile As String = "C:\Documents and Settings\All Users\allfiles.txt"
Try
' Create an instance of StreamReader to read from a file.
Dim SR As StreamReader = New StreamReader(lfile)
Dim str As String
'Read and display the lines from the file until the end of the file
Do
str = SR.ReadLine
If Not str = String.Empty Then ListBox1.Items.Add(str)
Loop Until str Is Nothing
SR.Close()
Catch ex As Exception
MsgBox("Reading file error ... " + vbCrLf + ex.Message())
End Try
(∆ιαβάζοντας ένα text αρχείο µε StreamReader και εµφανίζοντας τις γραµµές του σε ένα ListBox )
Aνάθεση Ονόµατος Αρχείου- SaveFileDialog
SaveFileDialog παρόµοιο µε OpenFileDialog
∆ίνει δυνατότητα απαγόρευσης overwritings.
Εvents
FileOK event
Private Sub SaveFileDialog1_FileOk(ByVal sender As Object, ByVal e As_
System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
If MessageBox.Show("Are you sure:", "SUR", MessageBoxButtons.YesNo) =_
Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub
HelpRequest event
[4]
2. Σώσιµο Αρχείου
(
My.Computer.FileSystem
sw = New StreamWriter(filename)
File.CreateText
My.Computer.FileSystem.OpenTextFileWriter)
Aποθήκευση αρχείου κειµένου
My.Computer.FileSystem component /
WriteAllText
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Button2.Click
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt
If (SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName,_
TextBox2.Text,False)
End If
End Sub
(∆ηµιουργώντας ένα text αρχείο µε Μy.Computer.FileSystem.WriteAllText και SaveFileDialog )
WriteAllText µε 3 παραµέτρους:
1. το όνοµα του αρχείου που επιλέγει ο χρήστης (εδώ, ο χρήστης δίνει το όνοµα του αρχείου µέσω του
SaveFileDialog1).
2. από πού θα πάρει τα δεδοµένα για να τα γράψει στο αρχείο (εδώ, το Τext του TextBox2).
3. προσδιορίζει αν θα γίνει προσάρτηση στο τυχόν υπάρχον κείµενο ή όχι (append the text or overwrite the
existing text - εδώ η τιµή False προσδιορίζει ότι θα γίνει overwrite the existing text).
The StreamWriter Class /
WriteLine
StreamWriter Class παρόµοια µε τηνStreamReader Class
Μέθοδοι εγγραφής, Write(String), WriteLine(String) - γράφει το string µε line terminator στο text stream.
Imports System.IO
∆ηµιουργώντας/ ∆ιαβάζοντας ένα text αρχείο µε StreamWriter και WriteLine. /StreamReader και ReadLine
Aποθήκευση στοιχείων (γραµµών) Πίνακα της βάσης σε αρχείο
Dim sw As StreamWriter
sw = File.CreateText(SaveFileDialog1.FileName)
For Each dr As DataRow In NorthwindDataSet.Tables("Customers").Rows
sw.WriteLine( dr("CompanyName").ToString ())
Next
sw.Close()
Aνάγνωση στοιχείων από αρχείο για εισαγωγή (γραµµών) σε Πίνακα της βάσης
Dim sr As StreamReader
sr = File.OpenText(SaveFileDialog1.FileName)
Dim P As Array
Do Until sr.EndOfStream 'read lines from file
LineOfText = sr.ReadLine()
P = strLine.Split(",")'split fields into Array
'εισαγωγή στον Πίνακα µε την µέθοδο του Adapter.Insert(P(0), P(1),…. )
Loop
sw.Close()
[5]
4.Directory Information
The following examples demonstrates some of the main members of the DirectoryInfo class.
Imports System.IO
…
' Specify the directories you want to manipulate.
Dim dir As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
' Determine whether the directory exists.
If dir.Exists Then
MsgBox("That path exists already.")
Return
End If
'Create the directory.
dir.Create()
MsgBox("The directory was created successfully.")
Catch ex As Exception
MsgBox(String.Format("Create process failed: {0}", ex.ToString()))
End Try
...
' Try to delete the directory.
Dim dir As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
dir.Delete()
MsgBox("The directory was deleted successfully.")
Catch ex As Exception
MsgBox(String.Format("Delete process failed: {0}", ex.ToString()))
End Try
…
'Directory’s files (subfolders not included).
Dim dir As DirectoryInfo = New DirectoryInfo("c:\Documents And Settings\All Users")
Try
If Not dir.Exists Then MsgBox("Dir not found ..") Else MsgBox("Dir’s file”)
For Each fi As FileInfo In dir.GetFiles()
MsgBox("Name:" + fi.Name & " size:" & fi.Length)
Next
Catch ex As Exception
….
Μια Function που υπολογίζει το µέγεθος ενός Directory µπορεί να είναι η παρακάτω:
Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
' Add file sizes.
For Each fi As FileInfo In d.GetFiles()
Size += fi.Length
Next fi
' Add subdirectory sizes.
For Each dir As DirectoryInfo In d.GetDirectories()
Size += DirSize(dir)
' ΑΝΑ∆ΡΟΜΗ για κάθε subfolder
Next dir
Return Size
[6]
End Function 'DirSize
5.SQL’s Queries
USE Northwind
Action queries ( INSERT,DELETE,UPDATE )
DELETE Customers
WHERE Country IS NULL
ExecuteNonQuery
DELETE Orders
WHERE OrderDate < ’1/1/1998’
(But you’ll get an error, because you can’t delete rows from the Orders table that are referenced by rows in the Order Details table)
INSERT Customers (CustomerID, CompanyName) VALUES (’Cust1’, ’Company A’)
INSERT INTO SelectedProducts SELECT * FROM Products WHERE CategoryID = 4
(The INSERT INTO statement allows you to select columns from one table and insert them into another one with the same structure as the
output of the selection query.Note that you need not create the new table ahead of time)
UPDATE Customers SET Country=’United Kingdom’ WHERE Country =’UK’
Aggregate/scalar queries ( SELECT COUNT(),SUM(),AVG(),MIN(),MAX() )
SELECT COUNT(CustomerID) FROM Customers
WHERE Country = ’Germany’
The aggregate functions are used to summarize data from one or more tables.
ExecuteScalar
SELECT SUM(Quantity * UnitPrice * (1 - Discount)) FROM [Order Details]
WHERE ProductID = 11
SELECT SUM(Quantity), SUM(Quantity * UnitPrice * (1 - Discount)) FROM [Order Details]
WHERE ProductID = 11
Select queries ( SELECT )
SELECT DISTINCT CompanyName FROM Customers
WHERE Country = ’Germany’
You can also combine multiple conditions with the AND/OR operator.
ExecuteReader
SELECT * FROM Products WHERE UnitPrice IS NULL
SELECT CompanyName, ContactName, Country, City FROM Customers
ORDER BY Country, City
SELECT Orders.OrderID, [Order Details].ProductID,[Order Details].UnitPrice ,[Order Details].Quantity
(1 - [Order Details].Discount) AS SubTotal
FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID
(Because the Order Details table’s name contains spaces, it’s embedded in square brackets).
SELECT CompanyName FROM Customers WHERE Country IN (’Germany’, ’Austria’, ’Switzerland’)
SELECT OrderID, OrderDate, CompanyName FROM Orders
WHERE (OrderDate BETWEEN ’1/1/1997’ AND ’12/31/1997’)
JOIN (Left,Right, Inner)
FROM (left table) LEFT JOIN (right table) ON (left table).(field) = (right table).(field)
SELECT Customers.CompanyName, Orders.UnitPrice
[7]
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
Programming with ADO.NET
ADO.NET provides two basic methods of accessing data:
•
Stream-based data access (DataReader object)
•
Set-based data access (DataSet Structure)
1. DataReader
Submitting the data to the database with the stream-based approach, you must create the appropriate
INSERT/UPDATE/DELETE statements and then execute them against the database.
The client application reads the data returned by a query through the DataReader object and must
store it somehow at the client.
ADO.NET provides three core classes for accessing databases:
the Connection,
the Command, and
the DataReader.
The Connection –
… Using the SQL Server 2008 DBMS … Using OleDB Server -
Imports System.Data.SqlClient ή
Imports System.Data.OleDb
Use the Connection object to execute statements‘ against the database and then close the connection
To connect to a data source, you must specify a connection string the parameters of which might differ for
each provider and data source:
Dim CNstring As String
CNstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source c:\test\Northwind.mdb;"
'ή CNstring = "Data Source = localhost; Initial Catalog = Northwind; uid = user
name;password = user password")
(εναλλακτικά : CNstring = InputBox("Please enter a Connection String", "CN", CNstring)
If CNstring.Trim = "" Then Exit Sub
Dim CN As New OleDbConnection (CNstring) 'ή As New SqlConnection(CNstring)
If CNstring.Trim = "" Then Exit Sub
Try
CN.Open()
If CN.State = ConnectionState.Open Then
MsgBox("Connected to database " & CN.Database)
End If
Catch ex As Exception
MsgBox("Failed to open connection " & vbCrLf & ex.Message)
End Try
If CN.State = ConnectionState.Open Then CN.Close()
The Command
Dim SqlString As String
SqlString = "UPDATE Categories SET CategoryName = 'Tralala lalo'" &
" WHERE CategoryID = 3" 'MsgBox(SqlString)
[8]
Dim CMD As New OleDbCommand(SqlString,CN)
' ή SqlCommand
Try
If CN.State = ConnectionState.Closed Then CN.Open()
Dim rows As Integer = CMD.ExecuteNonQuery()
If rows = 1 Then
MsgBox("Table Categories updated successfully")
Else
MsgBox("Failed to update the Categories table")
End If
CMD.CommandText = "SELECT COUNT(*) FROM Categories"
count = CMD.ExecuteScalar()
MsgBox("Number of categories records: " & count.ToString())
Catch ex As Exception
MsgBox("Operation failed " & ex.Message & " " & CN.Database)
End Try
If CN.State = ConnectionState.Open Then CN.Close()
The Reader
SqlString = "SELECT * FROM Categories"
CMD.CommandText = SqlString
Try
If CN.State = ConnectionState.Closed Then CN.Open()
Dim Reader As OleDbDataReader
' ή SqlDataReader
Dim str As String
Reader = CMD.ExecuteReader()
While Reader.Read()
' process the current row in the result set
str = Convert.ToString ( Reader.Item("CategoryName") ) & vbTab
str & = Convert.ToString( Reader.Item("Description") ) & vbTab
ListBox1.Items.Add(str)
End While
Catch ex As Exception
MsgBox("Operation failed " & ex.Message)
End Try
If CN.State = ConnectionState.Open Then CN.Close()
HasRows This is a Boolean property that specifies whether there’s a result set to read data from. If
the query selected no rows at all, the HasRows property will return False.
FieldCount This property returns the number of columns in the current result set. Note that the
DataReader object doesn’t know the number of rows returned by the query.
Read This method moves the pointer in front of the next row in the result set. Use this method to
read the rows of the result set, usually from within a While loop
GetValue If you can’t be sure about the type of a column, use the GetValue method
GetName Use this method to retrieve the name of a column, which must be specified by its order
in the result set.
IsDbNull This method returns True if the column specified by its ordinal in the current row is Null
….
[9]
2. DataSet
(The process of building data-driven applications isn’t complicated and to a large extent is abstracted
by the Connection, Command, and DataReader classes.
The problem with these classes is that they don’t offer a consistent method for storing the data at the
client. You can store the data in a ListBox control. You can also create an ArrayList of custom objects.
The issue of storing data at the client isn’t pressing when the client application is connected to the
database and all updates take place in real time.
As soon as the user edits a row, the row is submitted to the database and no work is lost.)
To simplify the storage of data at the client, ADO.NET offers a powerful mechanism, the DataSet.
The set-based approach uses the same objects as the stream-based approach behind the scenes,
and it abstracts most of the grunt work required to set up a link to the database, retrieve the data, and
store it in the client computer’s memory.
You can also create DataSets and the supporting objects with the visual tools of the IDE.
You can think of the DataSet as a small database (it isn’t actually) that lives in memory. The DataSet
lets you copy a small section of the database at the client, work with it, and then submit the changes
made at the client back to the database.
Actually, it’s not the DataSet that submits the changes, but a class that’s used in tandem with the
DataSet: the DataAdapter class. DataSets are filled with DataAdapters,which is a container for
Connection and Command objects.
There are two ways to create a DataSet:
You can use the visual tools of Visual Studio or
Create a DataSet entirely from within your code
typed DataSet
untyped DataSet
untyped DataSet
Products1.Products.Rows(0).Item(”ProductName”)
typed DataSet
Dim productRow As Products.ProductsRow = Products1.Products.Rows(0)
productRow.ProductName
productRow.UnitPrice
The visual tools generate a number of classes on-the-fly, such as the ProductsRow class, and
expose them to your code. As soon as you enter the string productRow and the following period in the
code window, you will see the members of the ProductsRow class, which include the names of the
columns in the corresponding table.
Dim CNstring As String
CNstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =c:\test\Northwind.mdb; "
Dim CN As New OleDbConnection(CNstring)
Dim DS As New DataSet
Dim DACategories As New OleDbDataAdapter ' ή SqlDataAdapter
Dim SqlString As String = "SELECT * FROM Categories"
DACategories.SelectCommand = New OleDb.OleDbCommand(SqlString, CN)
' ή SqlClient.SqlCommand (SqlString)
DACategories.Fill(DS, "Categories")
Dim str As String
For Each r As DataRow In DS.Tables("Categories").Rows
' process prodRow row: π.χ. γραµµή 5 -> DS.Tables("Categories").Rows(5)
str = r.Item("CategoryName").ToString()str &= vbTab &
r.Item("Description").ToString()ListBox1.Items.Add(str)
Next
…………
[10]
Eστω ότι το Dataset λέγεται NorthwindDataSet και έχει γίνει µε Visual Tools.
To παρακάτω loop γράφει όλα τα CategoryNames του ‘πίνακα’ Categories µέσω
StreamWriter στο αρχείο µε όνοµα "onoma.txt").
Dim strWr As StreamWriter
strWr = File.CreateText("c:\test\onoma.txt")
Dim str As String
For Each r As DataRow In NorthwindDataSet.Tables("Categories").Rows
str= r ("CategoryName").ToString()
strWr.WriteLine(str)
Next
strWr.Close()
Προσπέλαση σε ένα πίνακα του dataset:
NorthwindDataSet.Tables(0) ή
NorthwindDataSet.Tables ("Categories") ή
NorthwindDataSet.Categories
Προσπέλαση σε γραµµή πίνακα:
NorthwindDataSet.Tables("Categories").Rows(5) '6η γραµµή
Προσπέλαση σε στοιχείο γραµµής πίνακα:
NorthwindDataSet.Tables("Categories").Rows(5).Item(1) ή
NorthwindDataSet.Tables("Categories").Rows(5).Item("CategoryName")
'6η γραµµή,CategoryName
Π.χ.
For Each r As DataRow In NorthwindDataSet.Categories.Rows
' process Categories Row r:
' r.Item("CategoryName")
' r.Item("Description"),and so on
Next
Παρακάτω εισάγεται µια γραµµή στον πίνακα Categories µέσω του
CategoriesTableAdapter - φυσικά αν δηµιουργεί duplicate values δεν γίνεται εισαγωγή
Dim LineofText As String ="Katigoria9,Perigrafi9"
Dim P As Array = LineofText.Split(",")
'P(0)="Katigoria9" P(1)="Perigrafi9"
Try
Me.CategoriesTableAdapter.Insert(P(0), P(1), Nothing)
Catch ex As Exception
MsgBox(ex.Message())
End Try
Aπαιτείται νέο Fill για να εµφανιστούν οι διαφορές στον client
[11]
Download