文件操作(预览版的方法,需要最新的方法请加群:224893194)

windows 8 Metro Style App中文件的操作都包含在

Windows 8 Metro Style App中文件操作都包含在Windows.Storage命名空间中,其中包括StorageFolder,StorageFile,FileIO等类库。

文件对象用StorageFile实现,文件头用StorageFolder实现,下面看下具体的用法及各类库下的属性他方法。

StorageFolder实现,下面看下具体的用法及各类库下的属性他方法。

要进行文件的操作,首先需要在appx mainfest 里面配置相应的权限,不然会出现异常。 C++对文件的操作采取的是异步读取的方式。http://blog.csdn.net/liuwumiyuhuiping/article/details/7553149

c# 参考:http://www.cnblogs.com/jing870812/archive/2012/04/09/2439578.html

创建一个文件

	StorageFolder^ storageFoler=KnownFolders::DocumentsLibrary;
	task<StorageFile^>(KnownFolders::DocumentsLibrary->CreateFileAsync("sample.txt", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ file)
	{

	});

KnownFolders提供了系统中常规的文件路径。
CreationCollisionOption提供了创建文件冲突时的操作选项。

FileIO对象负责文件的读写操作

写入文件

task<void>(FileIO::WriteTextAsync(_sampleFile,userContent)).then
				([this,userContent](void)
			{
				});


写入文件也包含以下几种操作:
    写入Buffer数据 WriteBufferAsync(IStorage File,IBuffer buffer)
    写入bytes字节数据 WriteBytesAsync(IStorage File,bytes[] byte)
    写入文本行 WriteLinesAsync(IStorageFile File, IIterable(String)) /WriteLinesAsync(IStorageFile File, IIterable(String), UnicodeEncoding) 
    写入字符串 WriteTextAsync(IStorageFile File,string content)

读取文件

		task<IBuffer^>(FileIO::ReadBufferAsync(_sampleFile)).then([this]
		(IBuffer^ buf)
			{
				DataReader^ dataReader=DataReader::FromBuffer(buf);
				Platform::String^ userContent;
				userContent=dataReader->ReadString(buf->Length);
		});

读取操作包含三种方式:

返回普通文本 ReadTextAsync(storageFile)/ReadTextAsync(storageFile,UnicodeEncoding)(返回指定的文本编码格式)
返回流 ReadBufferAsync(storageFile)

也可以通过流方式:

		task<IRandomAccessStream^>(_sampleFile->OpenAsync(FileAccessMode::Read)).then
			([this](IRandomAccessStream^ readStream)
			{
				DataReader^ dataReader=ref new DataReader(readStream);
				task<unsigned int>(dataReader->LoadAsync(readStream->Size)).then(
					[this,dataReader](unsigned int numBytesLoaded)
					{
						Platform::String^ fileContent = dataReader->ReadString(numBytesLoaded);
				});
		});
返回文本行:

ReadLinesAsync(storageFile)/ReadLinesAsync(storageFile,UnicodeEncoding)

posted @ 2012-05-10 12:48  sinian  阅读(194)  评论(0编辑  收藏  举报