Silverlight之文件 *** 作

Silverlight之文件 *** 作,第1张

概述大家都知道在Silverlight中无法直接使用System.IO进行 *** 作文件,当然这个是为了安全考虑,不过Silverlight提供了其他的 *** 作方法,原理近似,同样很简单。 提到Silverlight中的文件 *** 作,第一个肯定是独立存储Isolated Store,这个东东相当于于一个本地的小型存储空间,通过它可以把一些不重要的数据(用户的一些配置信息或      大家都知道在Silverligh 大家都知道在Silverlight中无法直接使用System.IO进行 *** 作文件,当然这个是为了安全考虑,不过Silverlight提供了其他的 *** 作方法,原理近似,同样很简单。 提到Silverlight中的文件 *** 作,第一个肯定是独立存储Isolated Store,这个东东相当于于一个本地的小型存储空间,通过它可以把一些不重要的数据(用户的一些配置信息或   

  大家都知道在Silverlight中无法直接使用System.IO进行 *** 作文件,当然这个是为了安全考虑,不过Silverlight提供了其他的 *** 作方法,原理近似,同样很简单。

  提到Silverlight中的文件 *** 作,第一个肯定是独立存储Isolated Store,这个东东相当于于一个本地的小型存储空间,通过它可以把一些不重要的数据(用户的一些配置信息或者文件)

  IsolatedStoragefile:

  保存在客户端,由于这个空间是可以在本地查看得到,同时用户也可以随意的删除这些文件件以及文件,所以不要存放重要的信息。

  IsolatedStoragefile.GetUserStoreForApplication();得到基于当前用户和当前应用程序的IsolatedStoragefile。

  IsolatedStoragefile.GetUserStoreForSite();得到基于当前website域的所有IsolatedStoragefile(不止一个Application的,可能同一个website下有多个xap文件,那么这些是共享的),这样就可以在多个Application中共享信息。

  下面先看下独立存储的规则:

  1.不同的XAP文件,在同一个website下并且在同一个文件夹有不同的独立存储文件

  2.如果Application在不同的site宿主,则有自己的独立存储文件

  3.如果使用不同的TestPage,使用同一个XAP,则使用同一个独立存储文件

  4.如果重命名XAP文件,则使用不同的独立存储文件

  5.如果修改版本信息,等其他的程序及配置信息,则还使用同一个独立存储文件

  6.如果替换一个名字一样的XAP文件,则还使用之前的独立存储文件

  IsolatedStoragefile *** 作文件的方法:

  CreateDirectory() 创建一个文件夹在Isolated Store,根据用户指定的名字。

  DeleteDirectory() 删除一个文件夹,根据用户指定的名字。

  Createfile() 创建一个文件,根据用户指定的名字,并且返回IsolatedStoragefileStream对象,可以用来进行写入 *** 作。

  Deletefile() 删除一个文件,根据指定的名字。

  Remove() 移除Isolated Store对象,包含所有的文件夹和文件。

  Openfile() 打开一个文件,并且返回IsolatedStoragefileStream对象。

  fileExists() 判断一个文件是否存在,返回true或者false。

  DirectoryExists() 判断一个文件夹是否存在,返回true或者false。

  Getfilenames() 获得根目录(指定的目录)下的所有文件名称,返回一个string的array。

  GetDirectorynames() 获得根目录(指定目录下)的所有文件夹名称,返回一个string的array

  使用IsolatedStoragefile读写数据:

  StreamWriter和StreamReader用来读取和写入文本信息;

  BinaryWriter和BinaryReader用来读取和写入二进制信息.

  例子:

  如果使用windows vista或者windows 7系统,则独立存储的文件在C:\Users\[Username]\AppData\LocalLow\Microsoft\Silverlight\is目录。

  当然在调试时候也可以看到,如下图:

  创建文件:

IsolatedStoragefile storagefile=IsolatedStoragefile.GetUserStoreForApplication();
IsolatedStoragefileStream myfs = storefile.Createfile(filePath);
using (StreamWriter mysw = new StreamWriter(myfs))
{
mysw.Writeline(content);
}

  通过使用IsolatedStoragefile.Createfile创建一个文件,得到返回的IsolatedStoragefileStream对象,使用该对象创建StreamWriter对象调用Writeline方法写入一行数据。

  读取文件:

                  //使用这个方法合并目录和文件路径
string path = System.IO.Path.Combine(this.txtDirectionname.Text,this.txtfilename.Text);
判断是否存在这个文件if (storagefile.fileExists(path))
{
创建一个读取流,参数为OpenIfile方法读取指定位置文件的流
StreamReader sw = new StreamReader(storagefile.Openfile(path,fileMode.Open,fileAccess.Read));
读取文件内容
this.txtfileContent.Text = sw.ReadToEnd();
}

  首先判断是否存在该文件,如果存在则调用IsolatedStoragefile.Openfile函数返回一个IsolatedStoragefileStream对象,使用该对象创建StreamReader对象调用ReadToEnd

  函数得到文本信息。

  删除文件:

 IsolatedStoragefile storagefile=IsolatedStoragefile.GetUserStoreForApplication();
storagefile.Deletefile(path);

  创建目录:

IsolatedStoragefile storagefile=IsolatedStoragefile.GetUserStoreForApplication();
storagefile.CreateDirectory(path);

  获得列目录(即获得指定目录或者整个应用程序的目录):

IsolatedStoragefile storagefile=IsolatedStoragefile.GetUserStoreForApplication();

storagefile.GetDirectorynames("*");当前的*表示获得所有的目录

  删除目录:

 IsolatedStoragefile storagefile=IsolatedStoragefile.GetUserStoreForApplication();
storagefile.DeleteDirectory(path);

  添加空间:

  默认的存储空间是1MB,当程序以OOB模式运行时候,则会增加到25MB,不管是 OOB还是Web模式,都是使用同一个独立存储。

  如果要增加存储空间,则调用IsolatedStoragefile.IncreaseQuotaTo()来增加到想要的空间大小,这里是按字节来算。

  使用该方法需要注意两点:

  1.该方法需要在事件中调用,切忌在Load中调用

  2.该方法增加的值需要大于当前的空间,否则会出现错误

  使用SolatedStoragefile.Quota得到当前独立存储的空间大小。

  使用IsolatedStoragefile.AvailableFreeSpace得到当前可用的独立存储空间大小。

  通过XmlSerializer存储Object对象:

  其实这个功能还是很好用的,也是很有用,通过XmlSerializer将对象进行序列化保存在文件中,当我们需要的时候再通过XmlSerializer进行反序列化得到使用的对象。

  XmlSerializer通过转换字节流对象来实现整个的序列化和反序列化,是可以针对任何Stream的。

  使用XmlSerializer步骤如下:

  1.添加System.Xml.Serializtion.dll

  2.类需要提供一个无参的构造函数

  3.类需要有公有的setter属性构成,当XmlSerializer进行序列化和反序列化的时候则会使用到这些属性,则忽略私有的字段

  下面来一个完整的例子:

  User实体类:

 public class User
{
string Firstname { get; set; }
string Lastname { public DateTime? DateOfBirth { public User(string firstname,255)">string lastname,DateTime? dateOfBirth)
{
Firstname = firstname;
Lastname = lastname;
DateOfBirth = dateOfBirth;
}
public User() { }
}
          XAML代码: GrID x:name =LayoutRoot Background =White GrID.ColumnDeFinitions ColumnDeFinition / ColumnDeFinition ColumnDeFinition / ColumnDeFinition / GrID.ColumnDeFinitions StackPanel GrID.Column =0 L                      

  XAML代码:

<GrID x:name="LayoutRoot" Background="White">
GrID.ColumnDeFinitionsColumnDeFinition></</StackPanel GrID.Column="0"ListBox ="lstUsers"ListBoxbutton Height="25" Content="Delete" x:name="btnDelete" Click="btnDelete_Click"buttonStackPanel="1"GrIDGrID.RowDeFinitionsRowDeFinitionsdk:Label ="lblFirstname"="Firstname" GrID.Row="0" GrID.Column="0" />
TextBox ="txtFirstname"="1" ="lblLastname"="Lastname"="1"="txtLastname"="lblDateOfBirth"="Date Of Birth"="2"sdk:DatePicker ="dateBirth" GrID.Row="Add or Update"="btnModify"="btnModify_Click"="3">

  效果图如下:

  

 

  左边一个ListBox显示所有的filename,可以进行删除,当选择一个ListItem项 则在右边显示对应的对象的信息.

  下面是Xaml.cs代码:

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())
{
得到选中的项对应的file
using (StreamReader sr = new StreamReader(store.Openfile(lstUsers.SelectedItem.ToString(),fileAccess.Read)))
{
进行反序列化 *** 作
User user = (User)serializer.Deserialize(sr);
txtFirstname.Text = user.Firstname;
txtLastname.Text = user.Lastname;
dateBirth.SelectedDate = user.DateOfBirth;
}
}
}

定义序列化对象,当前类型为User
private XmlSerializer serializer = new XmlSerializer(typeof(User));
voID IsolatedStoreByXmlSerializer_Loaded( {
得到所有的后缀为.user的文件
lstUsers.ItemsSource = store.Getfilenames(*.user");
}
}

private voID btnModify_Click(实例化对象,值为文本输入的值
User user = new User() { Firstname = txtFirstname.Text,Lastname = txtLastname.Text,DateOfBirth =dateBirth.SelectedDate};
得到创建文件的流using (StreamWriter sw = new StreamWriter(store.Createfile(user.Firstname + user.Lastname + .user")))
{
进行序列化 *** 作
serializer.Serialize(sw,user);
}
lstUsers.ItemsSource = store.Getfilenames(");
}

}

voID btnDelete_Click(如果选择的项不为空if (lstUsers.SelectedItem != null)
{
删除选中的文件
store.Deletefile(lstUsers.SelectedItem.ToString());
lstUsers.ItemsSource = store.Getfilenames(");
}
}
}
}

  在代码中实现的功能是,在右边可以进行新增一个file文件,在左边显示完整的file的列表,当选中一项会在右边显示其对应的详细信息,当然也可以进行删除 *** 作。

  IsolatedStorageSettings :

  可以看到在上边中使用IsolatedStoragefile多用来 *** 作文档等文件,在Silverlight中还提供了一个很有用的对象IsolatedStorageSettings,可以用来保存一些信息,这些信息是

  直观的,也就是可以直接拿来使用,该对象是一个键对值的形式存在,该对象提供了两个属性ApplicationSettings和SiteSettings,同样的前者表示当前Application的存储数据,

  后者表示当前website域的存储数据。这个对象有点类似于cookie的形式在存放,当你关闭网页,或者是重新登录,这些信息还都是存在的。

  例子:

             IsolatedStorageSettings userSettings = IsolatedStorageSettings.SiteSettings;
userSettings[fly"] = ";
userSettings[user"] = new User() { Firstname=wang",Lastname=Fly User user = (User)userSettings["];

  可以看到,Setting是不仅可以存放简单的数据,也可以存放复杂的类型。

  OpenfileDialog:

  没错,就是这个OpenfileDialog,和之前的使用方法一摸一样,同样是先打开选择窗体,选择文件,点击确定,处理文件。

  OpenfileDialog dialog = new OpenfileDialog();

  实例化OpenfileDialog;

  指定Dialog的筛选器类型字符串:

  dialog.Filter = "Text files (*.txt)|*.txt";

  选择不同类型的文件:

  dialog.Filter = "Bitmaps (*.bmp)|*.bmp|JPEGs (*.jpg)|*.jpg|All files (*.*)|*.*";

  或者:

  dialog.Filter = "Image files (*.bmp;*.jpg;*.gif)|*.bmp;*.jpg;*.gif";

  通常来说处理读取分为两类,文本和非文本,文本很简单直接使用OpenfileDialog.OpenText();如果是二进制的则需要使用OpenfileDialog.OpenRead()。

  读取文本:

 OpenfileDialog fileDialog = new OpenfileDialog();
fileDialog.Filter = Text files (*.txt)*.txt";
if (fileDialog.ShowDialog() == true)
{
using (StreamReader sr = fileDialog.file.OpenText())
{
lblMsg.Text = sr.ReadToEnd();
}
}

  是不是很简单呢。

  读取非文本(当前例子是Image):

 OpenfileDialog fileDialog = Images files (*.bmp;*.jpg;*.gif)|*.bmp;*.jpg;*.gifusing (IsolatedStoragefile store = IsolatedStoragefile.GetUserStoreForApplication())
{
using (Stream fileStream = fileDialog.file.OpenRead())
{
如果当前的文件超过了可使用的空间,则增加空间
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;
do
{
count = fileStream.Read(buffer,0,buffer.Length);
if (count > 0) storeStraem.Write(buffer,buffer.Length);
} while (count>0);
}
}
}
}

  首先使用OpenfileDialog.file.OpenRead()得到Stream流,判断当前流的长度和独立存储的可用空间大小,如果大于独立存储则增加独立存储空间;

  使用IsolatedStoragefile.Createfile创建文件并且得到IsolatedStoragefileStream对象;然后定了一个byte的数组用于读取文件流中的数据,暂且为1024字节长度,通过Stream.Read方法判断当前是否还存在未读取的数据,如果存在则使用IsolatedStoragefileStream.Write向文件中写入数据,并且使用循环来实现。

  并且OpenfileDialog支持多选,设置OpenfileDialog.Multiselect为ture则可实现多选,为false禁止多选,多选后使用OpenfileDialog.files属性得到。

  修改如下:

OpenfileDialog fileDialog = 遍历files,得到fileInfo对象
foreach (fileInfo file in fileDialog.files)
{
using (Stream fileStream = file.OpenRead())
{

if (fileStream.Length > store.AvailableFreeSpace)
{
store.IncreaseQuotaTo(fileStream.Length);
}
using (IsolatedStoragefileStream storeStraem = store.Createfile(fileDialog.file.name))
{
byte[] buffer = do
{
count = fileStream.Read(buffer,buffer.Length);
} while (count > 0);
}
}
}
}
}

  修改后的代码如上,添加了对文件的遍历 *** 作。

  通过Webservice上传和下载文件:

service端代码: /// summary /// 获取文件列表 /// /summary /// returns/returns [WebMethod] public string [] GetfileList() { // 得到指定目录下的所有文件列表 string [] files = Directory.Getfiles(filePat   

  service端代码:

 /// <summary>
/// 获取文件列表
</summary><returns></returns>
[WebMethod]
string[] GetfileList()
{
得到指定目录下的所有文件列表
string[] files = Directory.Getfiles(filePath);
for (int i = 0; i < files.Length; i++)
{
得到文件的名称
files[i] = Path.Getfilename(files[i]);
}
return files;
}

下载文件
<param name="filename">文件名称</param>byte[] Downloadfile(string filename)
{
string file = Path.Combine(filePath,filename);
using (fileStream myfs=new fileStream (file,fileMode.Open))
{
byte[] bytes=byte[myfs.Length];
myfs.Read(bytes,bytes.Length);
return bytes;
}
}

上传文件
<param name="bytes">文件字节数组</param>voID Uploadfile(string filename,255)">byte[] bytes)
{
{
myfs.Write(bytes,bytes.Length);
}
}

  以上有三个方法,分别为获得文件列表,上传文件和下载文件。

  看下前台的 *** 作:

    ="lstfile" Height="200"OrIEntation="Horizontal"="btnDownload"="btnDownload_Click"="DownLoad" WIDth="200" margin="5"="btnUpload"="btnUpload_Click"="Upload">

  就是一个StackPanel然后一个ListBox显示文件名称列表,两个按钮一个是上传一个是下载。

  Xaml后台代码如下:

class OperatefileByService : UserControl
{
public OperatefileByService()
{
InitializeComponent();
new RoutedEventHandler(OperatefileByService_Loaded);
}
private fileServiceSoapClIEnt proxy = new fileServiceSoapClIEnt();
voID OperatefileByService_Loaded( {
proxy.GetfileListCompleted += new EventHandler<GetfileListCompletedEventArgs>(proxy_GetfileListCompleted);
proxy.GetfileListAsync();
proxy.CloseAsync();
}

voID proxy_GetfileListCompleted( {
lstfile.ItemsSource = e.Result;
}

voID btnDownload_Click(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( {
if (e.Error == null)
{
得到下载的字节数据数组byte[] data = e.Result;
SavefileDialog saveDialog = (SavefileDialog)e.UserState;
using (Stream fs = saveDialog.Openfile())
{
fs.Write(data,data.Length);
}
}
}

voID btnUpload_Click( {
OpenfileDialog fileDialog = new OpenfileDialog();
if (fileDialog.ShowDialog()==try
{
using (Stream stream= fileDialog.file.OpenRead())
{
if (stream.Length < 5120000)
{
byte[] data = byte[stream.Length];
stream.Read(data,data.Length);
proxy.UploadfileCompleted +=new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_UploadfileCompleted);
proxy.UploadfileAsync(fileDialog.file.name,data);
}
else
{
MessageBox.Show(文件大于5MB");
}
}
}
catch (Exception)
{

throw;
}
}
}

voID proxy_UploadfileCompleted( {
if (e.Error==null)
{
proxy.GetfileListAsync();
}
}
}

  以上就是对文件的 *** 作总结,希望大家多给意见。

  本文来自wangyafei_it的博客,原文地址:http://www.cnblogs.com/ListenFly/archive/2012/01/31/2311289.HTML


(1存取小数据)
          private voID btnSaveSetting_Click(object sender,RoutedEventArgs e)              {              IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;              // txtinput is a TextBox defined in XAML.              if (!settings.Contains("userData"))              {              settings.Add("userData",txtinput.Text);              }              else              {              settings["userData"] = txtinput.Text;              }              settings.Save();              }    
          private voID btndisplaySetting_Click(object sender,RoutedEventArgs e)              {              // txtdisplay is a TextBlock defined in XAML.              txtdisplay.Text = "USER DATA: ";              if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))              {              txtdisplay.Text +=              IsolatedStorageSettings.ApplicationSettings["userData"] as string;              }              }    
(2读取图片)
          private PhotochooserTask photoTask;              // Constructor              public MainPage()              {              InitializeComponent();              photoTask = new PhotochooserTask();              photoTask.Completed += new EventHandler<PhotoResult>(photoTask_Completed);              }              voID photoTask_Completed(object sender,PhotoResult e)              {              if (e.TaskResult == TaskResult.OK)              {              BitmAPImage bmp = new BitmAPImage();              bmp.SetSource(e.ChosenPhoto);              Savetofile(bmp);              }              }              private voID btnSavefile_Click(object sender,RoutedEventArgs e)              {              photoTask.Show();              }              private voID Savetofile(BitmAPImage image)              {              using (IsolatedStoragefile store = IsolatedStoragefile.GetUserStoreForApplication())              {              WriteableBitmap bmImage = new WriteableBitmap(image);              if (!store.DirectoryExists("Images"))              {              store.CreateDirectory("Images");              }              using (IsolatedStoragefileStream isoStream =              store.Openfile(@"Images\userPhoto.jpg",fileMode.OpenorCreate))              {              Extensions.SaveJpeg(              bmImage,          isoStream,          bmImage.PixelWIDth,          bmImage.PixelHeight,          0,          100);              }              }              }              (3读取路径下文件)                         private BitmAPImage GetSavedImage()               {               BitmAPImage image;               using (IsolatedStoragefile store =               IsolatedStoragefile.GetUserStoreForApplication())               {               using (IsolatedStoragefileStream isoStream =               store.Openfile(@"Images\userPhoto.jpg",fileMode.Open))               {               image = new BitmAPImage();               image.SetSource(isoStream);               }               }               return image;               }               private voID btndisplayfile_Click(object sender,RoutedEventArgs e)               {               BitmAPImage bitmap = GetSavedImage();               if (bitmap != null)               {               // userImage is defined in MainPage.xaml               userImage.source = bitmap;               }               }        
总结

以上是内存溢出为你收集整理的Silverlight之文件 *** 作全部内容,希望文章能够帮你解决Silverlight之文件 *** 作所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1069278.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存