Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction
I wanted to package a text file with my app and then at run time be able to read it into the app. Youd think
this was fairly straightforward. This was so easy in WinForms and WPF, then got a bit trickier in Windows
Phone 7 with all that isolated storage stuff, and now WinRT has brought its own version of whats needed.
The code
I found several articles on MSDN that explained how to create a text file within the app and then save it
and read back from it, but I couldnt find anything that fitted my scenario exactly. With a bit of trial and
error, I finally came up with a version that worked:
Heres how I see it working (but see my Disclaimer at the end of this post).
In summary, the Package object is the container for a Metro app, and so Package.Current is the current
app (This seems to be similar to Application.Current in other technologies).
The InstalledLocation property of the Package identifies the path to where the app is stored.
The StorageFolder object has properties and methods that relate to a folder, and in this case the code
identifies the folder thats being used to store this app.
Similarly, the StorageFile object has properties and methods that relate to an individual file.
StorageFolder and StorageFile have obvious equivalents in the earlier technologies.
The GetFileAsync method locates the required file in the storage folder and assigns this file to the
StorageFile instance.
The Await expression signals that the GetFileAsync method will continue asynchronously (that is, it wont
make the app wait for the return of the file) . The method name GetCatalogItemsAsync uses the naming
convention of adding the suffix of Async to the method name. This indicates that the method contains
asynchronous code. Such a method will usually also make use of the Await expression and, in fact, the
code editor will display a message if you create such a method and dont use Await in it somewhere.
The ReadTextAsync method does what youd expect, and does it asynchronously.
Finally, in this example I chose to display the contents of the file in a TextBlock.
and this gives me a List (Of String) that I can manipulate and access to get at the individual items I need.
Summary
When you see the code in the Async method broken down into its steps, its fairly easy to follow, even
though the syntax is quite different from what youll have been used to. The logic is familiar, but theres a
whole load of new classes and objects to get to grips with. Happily, some familiar code, like the List
creation, is still fully usable.
Disclaimer
Im writing these blog posts early in 2012, while Windows 8 is still in Consumer Preview and Visual Studio
11 is still in Beta. Its highly likely that some things will change between now and the final release at the
end of the year. Much more likely is that somewhere along the way, Ill discover easier and better ways of
getting the results I want as I struggle my way through these early stages. So, basically, my point is that if
youve landed here many months after this post was written, please do keep in mind that there may be
better or more elegant techniques out there. But until smarter people than me get their books written to
help us all find our way, Im giving it my best shot.
Fuente: http://cs.vbcity.com/blogs/xtab/archive/2012/05/27/windows-8-metro-ui-apps-howto-package-a-text-file-with-your-app-and-access-it.aspx
Up until now, Ive used the local app data store to save and retrieve the user added data. I dont know if
this is the best way, but it works just fine.
That said, my instinct is that the best solution would be to have the combined packaged data plus any
added user data stored in a single file. (Although I half suspect that under the covers the mechanism for
saving data either as app data or as a file is pretty much the same). So, I knew what i wanted, but
actually figuring out how to do that turned out to be much more difficult than I expected. Not that the
coding technique is difficult once youve cracked it; I just couldnt find any examples that met my needs.
So I had several days of intermittent trial and error until I finally pinned it down.
So, if this is something you want to do in your app, heres the approach I came up with.
Step 1 The packaged file
When I talk about the packaged file, I mean a text file that contains some data that I always want to be
available at the start/first time run of the app.
Side Note: If I want to amend the contents of this file later, I can easily isolate it, make the changes and
(for now*) upload and update of the app to the Store.
Imports Windows.Storage
As you can see, the target file DefaultEntries.txt - has been stored in the Assets folder of the project. It
isnt necessary to do this. The text file could be stored in the project root, but in a project with a lot of files,
it makes sense to use folders.
The commenting in that snippet explains the steps involved in accessing and reading the file.
For the sake of demonstration, Ive used a button click event to call that async method and display the text
file contents in a text block. The data thats been read is now also stored at run time in the TextData string
variable.
Step 2 Adding users input data and saving to file
Obviously, in an ideal situation, the users data would be appended to the data that was just read from the
packaged file, and then the combined data written back to the packaged file. Im sure this can be done,
but I just couldnt find the way of identifying that packaged file in order to write to it. No matter what I tried,
I always came up with a File Not Found error. So my workaround is this:
So, for demonstration, Im taking some text from a text box that the user enters text into, and appending
that to the original chunk of text that was read from the packaged file.
Heres the code that does this:
Private Sub btnCombineData_Click_1(sender As Object, e As RoutedEventArgs)
WriteAppendedDataToFile("AmalgamatedData", TextData + Environment.NewLine +
txtUserInput.Text)
End Sub
over. (It is possible to delete the local storage file if necessary for example, if the user has an option to
start over. Ill cover that in another post).
Summary
One thing to think about is how many times youd want to run the ReadFromThePackagedFile method. In
most cases, youll probably only want to run this once. Because the saved file will contain all the
packaged file data, you wont usually want to run the ReadFromThePackagedFile method every time the
app runs. Ive put it in a button click, so have complete control, but in a real app youre not likely to ask the
user to do this. So, in this case youll need to test for the existence of the AmalgamatedData file before
letting that method run.
If Im completely honest, this did become one of those challenges where I could see halfway through that
there were going to be easier options such as simply reading the data from both files separately,
combining it in memory, and only saving the user data. But Id invested so much effort that I was darned
well going to make it work the way Id originally envisaged it! Possibly not a recipe for good programming,
but sometimes, you know, you just dont want to be beaten.
So, even if you dont want to use the whole combine and save approach Ive used here, I hope that you
find the individual parts read, write, create new file, dont overwrite existing file, etc useful, anyway.
Fuente: http://vbcity.com/blogs/xtab/archive/2013/02/23/windows-store-apps-read-fromand-write-to-files.aspx
Fuente: http://msdn.microsoft.com/es-es/library/windows/apps/hh994634.aspx
Sintaxis
JavaScript
C#
C++
VB
Copiar
Public ReadOnly Property LocalFolder As StorageFolder
Valor de propiedad
Tipo: StorageFolder
La carpeta del sistema de archivos que contiene los archivos.
Observaciones
Puede tener acceso a los archivos en el almacn local de datos de la aplicacin mediante
el protocolo "ms-appdata:///local/". Por ejemplo:
<img src="ms-appdata:///local/myFile.png" alt="" />
Ejemplos
Utilice el archivo API, como Windows.Storage.StorageFolder.CreateFileAsync |
createFileAsync y Windows.Storage.FileIO.WriteTextAsync | writeTextAsync, para
crear y actualizar un archivo del almacn local de datos de la aplicacin. Este ejemplo
crea un archivo denominado dataFile.txt en el contenedor localFolder y escribe la
fecha y hora actual en el archivo. El valor ReplaceExisting | replaceExisting de la
enumeracin CreationCollisionOption indica que el archivo se reemplazar si ya
existe.
A continuacin, este ejemplo abre el archivo dataFile.txt creado y lee la fecha del
archivo mediante Windows.Storage.FileIO.ReadTextAsync | readTextAsync.
JavaScript
C#
C++
VB
Copiar
Dim localFolder As Windows.Storage.StorageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder
' Write data to a file
Private Async Sub WriteTimestamp()
Dim formatter As DateTimeFormatter = New DateTimeFormatter("longtime")
Dim sampleFile As StorageFile = Await
localFolder.CreateFileAsync("dataFile.txt",
CreationCollisionOption.ReplaceExisting)
Await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
End Sub
' Read data from a file
Private Async Function ReadTimestamp() As Task
Try
Dim sampleFile As StorageFile = Await
localFolder.GetFileAsync("dataFile.txt")
Dim timestamp As string = Await FileIO.ReadTtextAsync(sampleFile)
' Data is contained in timestamp
Catch e1 As Exception
' Timestamp not found
End Try
End Function
Fuente:
http://msdn.microsoft.com/library/windows/apps/windows.storage.applicationdata.localfolde
r.aspx
// Composite setting
var composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";
localSettings.values["exampleCompositeSetting"] = composite;
JavaScript
Copiar
// Composite setting
var composite = localSettings.values["exampleCompositeSetting"];
if (!composite)
{
// No data
}
else
{
// Access data in composite["intVal"] and composite["strVal"]
}
Temas relacionados
Tarea
Cmo cargar recursos de archivos
Inicio rpido: datos mviles de aplicaciones
Inicio rpido: datos de aplicacin temporales
Conceptual
Acceder a datos de aplicaciones con Windows en tiempo de ejecucin
Referencia
Windows.Storage.ApplicationData
Windows.Storage.ApplicationDataCompositeValue
Windows.Storage.ApplicationDataContainer
Windows.Storage.ApplicationDataContainerSettings
Muestras
Ejemplo de los datos de la aplicacin
Fuente: http://msdn.microsoft.com/es-ES/library/windows/apps/hh465118.aspx
En los dispositivos Windows Phone se hace una copia de seguridad de los datos de
aplicaciones de manera predeterminada. Si no quieres que se haga una copia de
seguridad de un archivo, gurdalo en la carpeta LocalCache del almacenamiento local
de la aplicacin.
C#
C++
VB
Copiar
Imports Windows.Globalization.DateTimeFormatting
Private Async Sub WriteTimestamp()
Dim formatter As DateTimeFormatter = New DateTimeFormatter("longtime")
Dim sampleFile As StorageFile = Await
localFolder.CreateFileAsync("dataFile.txt",
CreationCollisionOption.ReplaceExisting)
Await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
End Sub
Temas relacionados
Tareas
Cmo cargar recursos de archivos
Inicio rpido: datos mviles de aplicaciones
Inicio rpido: datos de aplicacin temporales
Conceptual
Acceder a datos de aplicaciones con Windows en tiempo de ejecucin
Referencia
Windows.Storage.ApplicationData
Windows.Storage.ApplicationDataCompositeValue
Windows.Storage.ApplicationDataContainer
Windows.Storage.ApplicationDataContainerSettings
Muestras
Ejemplo de los datos de la aplicacin
Fuente: http://msdn.microsoft.com/es-ES/library/windows/apps/xaml/hh700361.aspx
En algunos casos, un tipo que habas usado en una aplicacin de escritorio de .NET
Framework no existe en .NET para aplicaciones de la Tienda Windows. En su lugar,
puedes usar un tipo de Windows en tiempo de ejecucin. Por ejemplo, la clase
System.IO.IsolatedStorage.IsolatedStorageSettings no se incluye en .NET para
aplicaciones de la Tienda Windows, pero la clase
Windows.Storage.ApplicationDataContainer ofrece un comportamiento similar para
almacenar la configuracin de las aplicaciones. En la seccin Convertir el cdigo
existente de .NET Framework, hay ejemplos de los cambios que podras tener que
efectuar.
Se hace referencia de forma automtica en tu proyecto al conjunto completo de
ensamblados para .NET para aplicaciones de la Tienda Windows cuando creas una
aplicacin de la Tienda Windows con C# o Visual Basic. Por consiguiente, puedes usar
cualquiera de los tipos compatibles con .NET para aplicaciones de la Tienda Windows
en el proyecto sin necesidad de iniciar accin alguna. Para obtener una lista de los
Por
Tipos de la interfaz de usuario en espacios de
nombres Windows.UI.Xaml.*
(por ejemplo, la clase Border se encuentra en el
espacio de nombres Windows.UI.Xaml.Controls)
Los tipos de E/S incluyen nuevos miembros para prestar compatibilidad a la nueva
palabra clave await en el modelo de programacin asincrnica.
Cambia
Por
Mtodo System.IO.Stream.ReadAsync
Mtodos
System.IO.Stream.BeginRead
Para obtener un ejemplo, consulta ReadAsync(Byte(),
y EndRead
Int32, Int32).
Mtodo System.IO.Stream.WriteAsync
Mtodos
System.IO.Stream.BeginWrite
Para obtener un ejemplo, consulta WriteAsync(Byte(),
y EndWrite
Int32, Int32).
Mtodo Dispose() en clases de E/S.
o bien
Using sr As StreamReader =
New StreamReader(Await
passedFile.OpenStreamForReadAsync())
While (nextLine = Await sr.ReadLineAsync()) <>
Nothing
contents.Append(nextLine)
End While
End Using
Mtodo
El mtodo ReadTextAsync de la clase
System.IO.File::ReadAllText Windows.Storage.PathIO
C#
VB
Copiar
Public Async Shared Sub ReadFileSamples()
' Read a file from package
Dim packageFolder As StorageFolder =
ApplicationModel.Package.Current.InstalledLocation
Dim packagedFile As StorageFile =
Await
packageFolder.GetFileAsync("FileInPackage")
' Read a file from AppData
Dim localFolder As StorageFolder =
ApplicationData.Current.LocalFolder
Dim localFile As StorageFile =
Await localFolder.GetFileAsync("FileInAppData
")
End Sub
Cambios de almacenamiento
Por
La propiedad LocalFolder de la clase
Windows.Storage.ApplicationData
Clase
System.IO.IsolatedStorage.IsolatedStorageFile Copiar
ApplicationData.Current.LocalFolder
Clase
System.IO.IsolatedStorage.IsolatedStorageSetti Copiar
ngs
ApplicationData.Current.LocalSettin
gs
Cambios de red
Cambia
Clase System.Net.WebClient
Por
Clase System.Net.Http.HttpClient para enviar
solicitudes HTTP y recibir respuestas HTTP
o bien
Tipos del espacio de nombres
Windows.Networking.BackgroundTransfer para
cargar o descargar gran cantidad de datos
Tipos del espacio de nombres
Windows.Networking.Sockets
Identificadores URI absolutos
Por
Mtodo
Mtodo Interlocked.MemoryBarrier del
System.Threading.Thread.MemoryBarrier espacio de nombres System.Threading
Propiedad
Propiedad
System.Threading.Thread.ManagedThread Environment.CurrentManagedThreadId en
Id
el espacio de nombres System
Propiedad
Propiedad CultureInfo.CurrentCulture en el
System.Threading.Thread.CurrentCulture espacio de nombres System.Globalization
Propiedad
Propiedad CultureInfo.CurrentUICulture en
System.Threading.Thread.CurrentUICultu
el espacio de nombres System.Globalization
re
Clase
Clase System.Threading.Timer
Windows.System.Threading.ThreadPoolTi
mer
Clase
Clase System.Threading.ThreadPool
Windows.System.Threading.ThreadPool
C#
VB
Copiar
Task.Run(
Sub()
' work goes here
End Sub)
C#
VB
Copiar
Await Task.Run(
Sub()
' work goes here
End Sub)
C#
VB
Task.Factory.StartNew(
Sub()
' work goes here
End Sub,
TaskCreationOptions.LongRunning)
Cambios de reflexin
Por
type.GetTypeInfo().Assembly
type.GetTypeInfo().DeclaredMethods
type.GetTypeInfo().GetDeclaredMethod("Meth
odName")
type.GetTypeInfo().DeclaredNestedTypes
Mtodo MethodInfo.CreateDelegate
Cambios de recursos
En algunos casos, un tipo administrado produce una excepcin que no est incluida en
.NET para aplicaciones de la Tienda Windows. En estos casos, puedes detectar la clase
primaria de la excepcin que no se incluye. Por ejemplo, en una aplicacin de escritorio,
detectas la excepcin UriFormatException para controlar un URI no vlido; pero en una
aplicacin de la Tienda Windows, detectas la excepcin FormatException porque
UriFormatException no se incluye en .NET para aplicaciones de la Tienda Windows.
FormatException es la clase primaria de UriFormatException.
Cambios de la WCF
Cambia
Mtodo
System.Xml.XmlConvert.ToDateTime
Interfaz System.ICloneable
Por
Mtodo XmlConvert.ToDateTimeOffset
Mtodo personalizado que devuelve el tipo
adecuado
Nueva instancia de la clase
System.Collections.ObjectModel.ReadOnlyCo
llection(Of T), que se ha creado como sigue:
Mtodos System.Array.AsReadOnly y C#
System.Collections.Generic.List<T>.As
VB
ReadOnly
Copiar
New ReadOnlyCollection(Of
String)(selectedList)
System.Collections
System.Collections.Concurrent
System.Collections.Generic
System.Collections.ObjectModel
System.Collections.Specialized
Windows.Foundation.Collections
Principal
System
System.ComponentModel
System.Dynamic
System.Numerics
System.Runtime
System.Runtime.ExceptionServices
System.Runtime.InteropServices
System.Runtime.InteropServices.ComTypes
System.Runtime.InteropServices.WindowsRuntime
System.Text
System.Text.RegularExpressions
Windows.ApplicationModel
Windows.ApplicationModel.Activation
Windows.ApplicationModel.Background
Windows.ApplicationModel.Core
Windows.ApplicationModel.Search
Windows.ApplicationModel.Store
Windows.Foundation
Windows.Foundation.Metadata
Windows.Management.Core
Windows.Management.Deployment
Windows.System
Windows.System.Display
Windows.System.RemoteDesktop
Windows.System.UserProfile
Windows.UI.WebUI
Windows.UI.Xaml
Windows.UI.Xaml.Hosting
Windows.UI.Xaml.Interop
Windows.UI.Xaml.Markup
Datos y contenido
System.ComponentModel.DataAnnotations
System.ComponentModel.DataAnnotations.Schema
System.Linq
System.Linq.Expressions
System.Runtime.Serialization
System.Runtime.Serialization.Json
System.Xml
System.Xml.Linq
System.Xml.Schema
System.Xml.Serialization
Windows.ApplicationModel.DataTransfer
Windows.ApplicationModel.DataTransfer.ShareTarget
Windows.Data.Html
Windows.Data.Json
Windows.Data.Xml.Dom
Windows.Data.Xml.Xsl
Windows.Web
Windows.Web.AtomPub
Windows.Web.Syndication
Windows.UI.Xaml.Data
Windows.UI.Xaml.Documents
Dispositivos
Windows.Devices.Enumeration
Windows.Devices.Enumeration.Pnp
Windows.Devices.Geolocation
Windows.Devices.Input
Windows.Devices.Portable
Windows.Devices.Printers.Extensions
Windows.Devices.Sensors
Windows.Devices.Sms
Diagnstico
System.Diagnostics
System.Diagnostics.CodeAnalysis
System.Diagnostics.Contracts
System.Dianostics.Tracing
Windows.Foundation.Diagnostics
Archivos y carpetas
System.IO
System.IO.Compression
Windows.Storage
Windows.Storage.AccessCache
Windows.Storage.BulkAccess
Windows.Storage.Compression
Windows.Storage.FileProperties
Windows.Storage.Pickers
Windows.Storage.Pickers.Provider
Windows.Storage.Provider
Windows.Storage.Search
Windows.Storage.Streams
Globalizacin
System.Globalization
Windows.Globalization
Windows.Globalization.Collation
Windows.Globalization.DateTimeFormatting
Windows.Globalization.Fonts
Windows.Globalization.NumberFormatting
Grficos
Windows.Graphics.Display
Windows.Graphics.Imaging
Windows.UI.Xaml.Media
Windows.UI.Xaml.Media.Animation
Windows.UI.Xaml.Media.Imaging
Windows.UI.Xaml.Shapes
Para instalar los espacios de nombres siguientes, abre el proyecto en Visual Studio 2012
o posterior, elige Administrar paquetes NuGet en el men Proyecto y busca en lnea el
paquete Microsoft.Composition.
System.Composition
System.Composition.Convention
System.Composition.Hosting
System.Composition.Hosting.Core
Multimedia
Windows.Media
Windows.Media.Capture
Windows.Media.Devices
Windows.Media.MediaProperties
Windows.Media.Playlists
Windows.Media.PlayTo
Windows.Media.Protection
Windows.Media.Transcoding
Windows.UI.Xaml.Media
Redes
System.Net
System.Net.Http
System.Net.Http.Headers
System.Net.NetInformation
System.ServiceModel
System.ServiceModel.Channels
System.ServiceModel.Description
System.ServiceModel.Dispatcher
System.ServiceModel.Security
System.ServiceModel.Security.Tokens
Windows.Networking
Windows.Networking.BackgroundTransfer
Windows.Networking.Connectivity
Windows.Networking.NetworkOperators
Windows.Networking.Proximity
Windows.Networking.PushNotifications
Windows.Networking.Sockets
Presentacin
Windows.UI
Windows.UI.ApplicationSettings
Windows.UI.Core
Windows.UI.Core.AnimationMetrics
Windows.UI.Notifications
Windows.UI.Popups
Windows.UI.StartScreen
Windows.UI.Text
Windows.UI.ViewManagement
Windows.UI.Xaml
Windows.UI.Xaml.Controls
Windows.UI.Xaml.Controls.Primitives
Windows.UI.Xaml.Documents
Windows.UI.Xaml.Media.Animation
Windows.UI.Xaml.Media.Media3D
Windows.UI.Xaml.Navigation
Impresin
Windows.Graphics.Printing
Windows.Graphics.Printing.OptionDetails
Windows.UI.Xaml.Printing
Reflexin
System.Reflection
System.Reflection.Context
System.Reflection.Emit
Recursos
System.Resources
Windows.ApplicationModel.Resources
Windows.ApplicationModel.Resources.Core
Windows.ApplicationModel.Resources.Management
Windows.UI.Xaml.Resources
Seguridad
System.Security
System.Security.Principal
Windows.Security.Authentication.OnlineId
Windows.Security.Authentication.Web
Windows.Security.Credentials
Windows.Security.Credentials.UI
Windows.Security.Cryptography
Windows.Security.Cryptography.Certificates
Windows.Security.Cryptography.Core
Windows.Security.Cryptography.DataProtection
Windows.Security.ExchangeActiveSyncProvisioning
Social
Windows.ApplicationModel.Contacts
Windows.ApplicationModel.Contacts.Provider
Subprocesamiento
System.Threading
System.Threading.Tasks
System.Threading.Tasks.DataFlow
Windows.System.Threading
Windows.System.Threading.Core
Windows.UI.Xaml.Automation
Windows.UI.Xaml.Automation.Peers
Windows.UI.Xaml.Automation.Provider
Windows.UI.Xaml.Automation.Text
System.Windows.Input
Windows.UI
Windows.UI.Input
Windows.UI.Input.Inking
Windows.UI.Xaml.Controls.Primitives
Windows.UI.Xaml.Input
Windows.UI.Xaml.Media
Windows.UI.Xaml.Media.Animation
Windows.UI.Xaml.Media.Media3D
Lenguaje y compiladores
Microsoft.CSharp.RuntimeBinder
Microsoft.VisualBasic
Microsoft.VisualBasic.CompilerServices
System.CodeDom.Compiler
System.Runtime.CompilerServices
System.Runtime.Versioning
Vea tambin
Conceptos
API de .NET para aplicaciones de la Tienda Windows
Crear componentes de Windows en tiempo de ejecucin en C# y Visual Basic
Otros recursos
Compatibilidad de .NET Framework con las aplicaciones de la Tienda Windows y Windows en
tiempo de ejecucin
Fuente: http://msdn.microsoft.com/es-es/library/br230302.aspx#storage