Silverlight file operation in asp.net

Source: Internet
Author: User
Tags datetime serialization silverlight

Referring to file operations in Silverlight, the first is definitely isolated storage isolated store, which is equivalent to a local small storage space, through which you can put some unimportant data (user's configuration information or files)

IsolatedStorageFile:


Save on the client, because this space can be viewed locally, and users can delete these files and files at will, so do not store important information.

Isolatedstoragefile.getuserstoreforapplication (); Gets the isolatedstoragefile based on the current user and the current application.

Isolatedstoragefile.getuserstoreforsite (); Obtains all isolatedstoragefile based on the current website domain (more than one application, There may be multiple XAP files under the same website, which are shared, so that information can be shared across multiple application.

Let's look at the rules for isolated storage:

1. Different xap files, under the same website and with separate storage files in the same folder

2. If application is in a different site host, it has its own isolated storage file

3. If you use a different testpage and use the same xap, use the same isolated storage file

4. If you rename the Xap file, use a different isolated storage file

5. If you modify the version information, and other programs and configuration information, you also use the same isolated storage file

6. If you replace a XAP file with the same name, you will also use the previously isolated storage file


IsolatedStorageFile How to manipulate files:

CreateDirectory () creates a folder at the isolated Store, according to the user-specified name.

DeleteDirectory () Deletes a folder, based on the user-specified name.

CreateFile () Creates a file that can be used to write according to the user-specified name and return the IsolatedStorageFileStream object.

DeleteFile () deletes a file, according to the specified name.

Remove () removes the isolated store object, including all folders and files.

OpenFile () opens a file and returns the IsolatedStorageFileStream object.

FileExists () Determines whether a file exists, returns TRUE or false.

DirectoryExists () determines whether a folder exists, returns True or false.

GetFileNames () gets all the file names under the root directory (the specified directory), and returns an array of string.

GetDirectoryNames () gets all the folder names of the root directory (under the specified directory), and returns an array of string

Use IsolatedStorageFile to read and write data:

StreamWriter and StreamReader are used to read and write text messages;

BinaryWriter and BinaryReader are used to read and write binary information.


Example:

If you are using Windows Vista or a Windows 7 system, the files that are stored separately are in the C:users[username]appdatalocallowmicrosoftsilverlightis directory.

Of course, you can also see in the debugging, the following figure:


To create a file:

  code is as follows copy code

IsolatedStorageFile storagefile= Isolatedstoragefile.getuserstoreforapplication ();
  IsolatedStorageFileStream MYFS = StoreFile.CreateFile ( FilePath);
             using (StreamWriter MYSW = new StreamWriter (MYFS))
              {
                  MYSW. WriteLine (content);
             }

 

By using Isolatedstoragefile.createfile to create a file, get the returned IsolatedStorageFileStream object, use the object to create the StreamWriter object to invoke the WriteLine method to write a row of data.

Read file:

The code is as follows Copy Code

Use this method to merge directory and file paths
String path = System.IO.Path.Combine (This.txtdirectionname.text,this.txtfilename.text);
To determine if this file exists
if (storagefile.fileexists (path))
{
Creates a read stream in which the parameter reads the stream of the specified location file for the Openifile method
StreamReader SW = new StreamReader (storagefile.openfile (Path, FileMode.Open, FileAccess.Read));
Read File contents
This.txtFileContent.Text = SW. ReadToEnd ();
}

First determine if the file exists, If present, the call to the Isolatedstoragefile.openfile function returns a IsolatedStorageFileStream object that is used to create the StreamReader object call ReadToEnd

function to get textual information.

To delete a file:

The code is as follows Copy Code

IsolatedStorageFile storagefile=isolatedstoragefile.getuserstoreforapplication ();
Storagefile.deletefile (path);

To create a directory:

The code is as follows Copy Code

IsolatedStorageFile storagefile=isolatedstoragefile.getuserstoreforapplication ();
Storagefile.createdirectory (path);

Get the column directory (that is, get the directory for the specified directory or the entire application):

The code is as follows Copy Code

IsolatedStorageFile storagefile=isolatedstoragefile.getuserstoreforapplication ();

Storagefile.getdirectorynames ("*");/current * means to get all the catalogs

To delete a directory:

The code is as follows Copy Code

IsolatedStorageFile storagefile=isolatedstoragefile.getuserstoreforapplication ();
Storagefile.deletedirectory (path);


Add Space:

The default storage space is 1MB, and when the program runs in OOB mode, it increases to 25MB, either OOB or Web mode, using the same isolated storage.

If you want to increase your storage space, call Isolatedstoragefile.increasequotato () to increase the amount of space you want, which is measured in bytes.

Use this method to note two points:

1. This method needs to be called in the event, avoid calling in load

2. The added value of this method needs to be greater than the current space, otherwise there will be an error

Use Solatedstoragefile.quota to get the space size of the current isolated storage.

Use Isolatedstoragefile.availablefreespace to get the current amount of isolated storage space available.


To store object objects by XmlSerializer:

In fact, this function is very useful, but also very helpful, by XmlSerializer the object to be serialized in the file, when we need to use the XmlSerializer to deserialize the object used.

XmlSerializer can be used for any stream by converting the byte stream object to implement the entire serialization and deserialization.


Use the XmlSerializer steps as follows:

1. Add System.Xml.Serializtion.dll

2. Class needs to provide a parameterless constructor

3. Classes need to have public setter properties, which are used when XmlSerializer is serialized and deserialized, ignoring private fields

Here's a complete example:

User entity class:

The code is as follows Copy Code

public class User
{
public string FirstName {get; set;}
public string LastName {get; set;}
Public DateTime? dateOfBirth {get; set;}
Public User (String firstName, String lastName, DateTime? dateofbirth)
{
FirstName = FirstName;
LastName = LastName;
dateOfBirth = dateOfBirth;
}
Public User () {}
}

XAML Code:

The code is as follows Copy Code

<grid x:name= "LayoutRoot" background= "White" >
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<stackpanel grid.column= "0" >
<listbox x:name= "Lstusers" ></ListBox>
<button height= "content=" "Delete" X:name= "Btndelete" click= "Btndelete_click" ></Button>
</StackPanel>
<stackpanel grid.column= "1" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<sdk:label x:name= "Lblfirstname" content= "FirstName" grid.row= "0" grid.column= "0"/>
<textbox x:name= "txtFirstName" grid.row= "0" grid.column= "1"/>
<sdk:label x:name= "Lbllastname" content= "LastName" grid.row= "1" grid.column= "0"/>
<textbox x:name= "Txtlastname" grid.row= "1" grid.column= "1"/>
<sdk:label x:name= "Lbldateofbirth" content= "Date of Birth" grid.row= "2" grid.column= "0"/>
<sdk:datepicker x:name= "Datebirth" grid.row= "2" grid.column= "1"/>
<button height= "content=" "Add or Update" x:name= "btnmodify" click= "Btnmodify_click" grid.row= "3" grid.column= "1" ></Button>
</Grid>
</StackPanel>
</Grid>

The effect chart is as follows:

A listbox on the left shows all the filename, which can be deleted, and when a ListItem item is selected, the corresponding object's information is displayed on the right.

Here's the Xaml.cs code:

The code is as follows Copy Code

public partial class Isolatedstorebyxmlserializer:usercontrol
{
Public Isolatedstorebyxmlserializer ()
{
InitializeComponent ();
This. Loaded + = new Routedeventhandler (isolatedstorebyxmlserializer_loaded);
This.lstUsers.SelectionChanged + = new SelectionChangedEventHandler (lstusers_selectionchanged);
}

void Lstusers_selectionchanged (object sender, SelectionChangedEventArgs e)
{
using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
{
Gets the selected item corresponding to the file
using (StreamReader sr = new StreamReader (store). OpenFile (LstUsers.SelectedItem.ToString (), FileMode.Open, FileAccess.Read))
{
To deserialize an operation
User user = (user) serializer. Deserialize (SR);
Txtfirstname.text = user. FirstName;
Txtlastname.text = user. LastName;
datebirth.selecteddate = user. dateOfBirth;
}
}
}

       //Define serialization object, current type is User
        Private XmlSerializer serializer = new XmlSerializer (typeof (User));
        void isolatedstorebyxmlserializer_loaded (object sender, RoutedEventArgs e)
        {
             using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
            {
                //Get all files with the suffix. User
                 Lstusers.itemssource = store. GetFileNames ("*.user");
           }
       }

private void Btnmodify_click (object sender, RoutedEventArgs e)
{
Instantiate an object with a value of text input
User user = new user () {FirstName = Txtfirstname.text, LastName = Txtlastname.text, dateOfBirth =datebirth.selecteddate};
using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
{
Get the stream to create the file
using (StreamWriter sw = new StreamWriter (store). CreateFile (user. FirstName + user. LastName + ". User"))
{
To perform a serialization operation
Serializer. Serialize (SW, user);
}
Lstusers.itemssource = store. GetFileNames ("*.user");
}

}

private void Btndelete_click (object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
{
If the selected item is not empty
if (Lstusers.selecteditem!= null)
{
Delete the selected files
Store. DeleteFile (LstUsers.SelectedItem.ToString ());
Lstusers.itemssource = store. GetFileNames ("*.user");
}
}
}
}


The function implemented in the code is that a new file file is available on the right, a complete list of files is displayed on the left, and an item is selected to display its corresponding details on the right and, of course, can be deleted.


Isolatedstoragesettings:

You can see the use of IsolatedStorageFile in the top to manipulate documents and other files, in Silverlight also provides a useful object isolatedstoragesettings, can be used to save some information, this information is

Intuitive, that is, can be directly used, the object is a key to the form of a value, the object provides two properties ApplicationSettings and Sitesettings, the same as the former represents the current application storage data,

The latter represents the stored data for the current website domain. This object is a bit like a cookie in the store, and when you close the page, or log back in, the information is still there.

Example:

The code is as follows Copy Code

Isolatedstoragesettings usersettings = isolatedstoragesettings.sitesettings;
usersettings["Fly"] = "Fly";
usersettings["User" = New user () {firstname= "Wang", lastname= "Fly", dateofbirth=datetime.now};
User user = (user) usersettings["user"];

As you can see, setting is not only able to store simple data, but also to store complex types.

OpenFileDialog:

Yes, this is the OpenFileDialog, and the previous use of the same way, the same is the first to open the selection form, select files, click OK, processing files.

The code is as follows Copy Code

OpenFileDialog dialog = new OpenFileDialog ();

Instantiation of OpenFileDialog;

Specifies the filter type string for dialog:

Dialog. Filter = "Text Files (*.txt) |*.txt";

Select different types of files:

The code is as follows Copy Code

Dialog. Filter = "bitmaps (*.bmp) |*.bmp| JPEGs (*.jpg) |*.jpg| All Files (*.*) |*.* ";

Or:


Dialog. Filter = "Image Files (*.bmp;*.jpg;*.gif) |*.bmp;*.jpg;*.gif";

Typically, processing reads can be divided into two categories, text and Openfiledialog.opentext, and text is simple to use directly (), and Openfiledialog.openread () is required if binary is used.

Read text:

The code is as follows Copy Code

OpenFileDialog FileDialog = new OpenFileDialog ();
Filedialog.filter = "Text Files (*.txt) *.txt";
if (filedialog.showdialog () = = True)
{
using (StreamReader sr = FileDialog.File.OpenText ())
{
Lblmsg.text = Sr. ReadToEnd ();
}
}

Is it simple?

Read non-text (current example is image):

The code is as follows Copy Code

OpenFileDialog FileDialog = new OpenFileDialog ();
Filedialog.filter = "Images Files (*.bmp;*.jpg;*.gif) |*.bmp;*.jpg;*.gif";
if (filedialog.showdialog () = = True)
{
using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
{
using (Stream FileStream = FileDialog.File.OpenRead ())
{
Increase space if the current file exceeds the available space
if (Filestream.length > Store. Availablefreespace)
{
Store. Increasequotato (filestream.length);
}
using (IsolatedStorageFileStream Storestraem=store. CreateFile (FileDialog.File.Name))
{
byte [] buffer=new byte[1024];
int count = 0;
Todo
{
Count = FileStream.Read (buffer,0,buffer. Length);
if (Count > 0) storestraem.write (buffer,0,buffer. Length);
while (count>0);
}
}
}
}

First, the stream flow is obtained by using OpenFileDialog.File.OpenRead (), the length of the current stream and the available space of the isolated storage are determined, and the independent storage space is increased if it is larger than the isolated storage.

Use Isolatedstoragefile.createfile to create the file and get the IsolatedStorageFileStream object; then a byte array is used to read the data in the file stream for 1024 words.

Section length, the Stream.read method is used to determine whether unread data is currently present, and if so, write data to the file using Isolatedstoragefilestream.write, and use loops to implement it.


and OpenFileDialog support multiple-selection, set Openfiledialog.multiselect to Ture can be implemented multiple-select, to False prohibit multiple-selection, after the use of openfiledialog.files properties.

Modified as follows:

The code is as follows Copy Code

OpenFileDialog FileDialog = new OpenFileDialog ();
Filedialog.filter = "Images Files (*.bmp;*.jpg;*.gif) |*.bmp;*.jpg;*.gif";
if (filedialog.showdialog () = = True)
{
using (IsolatedStorageFile store = isolatedstoragefile.getuserstoreforapplication ())
{
Traverse files to get FileInfo objects
foreach (FileInfo file in Filedialog.files)
{
using (Stream fileStream = file. OpenRead ())
{
Increase space if the current file exceeds the available space
if (Filestream.length > Store. Availablefreespace)
{
Store. Increasequotato (filestream.length);
}
using (IsolatedStorageFileStream Storestraem = store. CreateFile (FileDialog.File.Name))
{
byte[] buffer = new byte[1024];
int count = 0;
Todo
{
Count = filestream.read (buffer, 0, buffer. Length);
if (Count > 0) storestraem.write (buffer, 0, buffer). Length);
while (Count > 0);
}
}
}
}
}

The modified code, as above, adds a traversal of the file.

Upload and download files via WebService:


Service-Side code:

The code is as follows Copy Code

<summary>
Get file List
</summary>
<returns></returns>
[WebMethod]
Public string[] Getfilelist ()
{
Get a list of all the files in the specified directory
string[] files = directory.getfiles (FilePath);
for (int i = 0; i < files. Length; i++)
{
Get the name of the file
Files[i] = Path.getfilename (Files[i]);
}
return files;
}

<summary>
Download files
</summary>
<param name= "FileName" > File name </param>
<returns></returns>
[WebMethod]
Public byte[] DownloadFile (string fileName)
{
string file = Path.Combine (filepath,filename);
using (FileStream myfs=new FileStream (File,filemode.open))
{
Byte[] Bytes=new Byte[myfs. Length];
Myfs. Read (bytes,0,bytes. Length);
return bytes;
}
}

<summary>
Uploading files
</summary>
<param name= "FileName" > File name </param>
<param name= "bytes" > file byte array </param>
[WebMethod]
public void UploadFile (string filename,byte[] bytes)
{
string file = Path.Combine (filepath,filename);
using (FileStream myfs=new FileStream (file,filemode.create))
{
Myfs. Write (bytes, 0, bytes. Length);
}
}

There are three ways to get a list of files, upload files, and download files, respectively.

Look at the operation of the front desk:

The code is as follows Copy Code

<stackpanel x:name= "LayoutRoot" background= "White" >
<listbox x:name= "Lstfile" height= "></ListBox>"
<stackpanel orientation= "Horizontal" >
<button x:name= "Btndownload" click= "Btndownload_click" content= "DownLoad" height= "" width= "" margin= "5" > </Button>
<button x:name= "Btnupload" click= "Btnupload_click" content= "Upload" height= "" width= "" margin= "5" ></ Button>
</StackPanel>
</StackPanel>

It's a StackPanel. Then a listbox displays a list of file names, two buttons one is uploaded and one is the download.

The code is as follows Copy Code

The XAML background code is as follows:

public partial class Operatefilebyservice:usercontrol
{
Public Operatefilebyservice ()
{
InitializeComponent ();
This. Loaded + = new Routedeventhandler (operatefilebyservice_loaded);
}
Private Fileservicesoapclient proxy = new Fileservicesoapclient ();
void Operatefilebyservice_loaded (object sender, RoutedEventArgs e)
{
Proxy. getfilelistcompleted + = new eventhandler<getfilelistcompletedeventargs> (proxy_getfilelistcompleted);
Proxy. Getfilelistasync ();
Proxy. Closeasync ();
}

void Proxy_getfilelistcompleted (object sender, Getfilelistcompletedeventargs e)
{
Lstfile.itemssource = E.result;
}

private void Btndownload_click (object sender, RoutedEventArgs e)
{
if (Lstfile.selectedindex!=-1)
{
String fileName = LstFile.SelectedItem.ToString ();
SaveFileDialog Savedialog = new SaveFileDialog ();
Savedialog.defaultext = "JPG";
if (savedialog.showdialog () = = True)
{
Proxy. downloadfilecompleted + = new eventhandler<downloadfilecompletedeventargs> (proxy_downloadfilecompleted);
Proxy. DownloadFileAsync (FileName, Savedialog);
}
}
}

void Proxy_downloadfilecompleted (object sender, Downloadfilecompletedeventargs e)
{
if (E.error = null)
{
Get the downloaded byte data array
byte[] data = E.result;
SaveFileDialog Savedialog = (SaveFileDialog) e.userstate;
using (Stream fs = Savedialog.openfile ())
{
Fs. Write (data, 0, data. Length);
}
}
}

private void Btnupload_click (object sender, RoutedEventArgs e)
{
OpenFileDialog FileDialog = new OpenFileDialog ();
if (Filedialog.showdialog () ==true)
{
Try
{
using (Stream stream= fileDialog.File.OpenRead ())
{
if (stream. Length < 5120000)
{
byte[] data = new Byte[stream. Length];
Stream. Read (data, 0, data.) Length);
Proxy. uploadfilecompleted +=new eventhandler<system.componentmodel.asynccompletedeventargs> (proxy_ uploadfilecompleted);
Proxy. Uploadfileasync (fileDialog.File.Name, data);
}
Else
{
MessageBox.Show ("File greater than 5MB");
}
}
}
catch (Exception)
{

Throw
}
}
}

void Proxy_uploadfilecompleted (object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.error==null)
{
Proxy. Getfilelistasync ();
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.