Sei sulla pagina 1di 37

Windows Store Apps - How to access text files

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.

Dealing with lists


As it happened, my text file was a long list of strings, so displaying them all in the text block wasnt what I
wanted. So, in this case I used the same kind of code approach that Ive used in the past:

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

Windows Store Apps: Read from and Write to files


Background
I dont know why, but Ive found that getting to grips with reading and writing to files in Windows Store apps
has been quite a struggle for me. When I say reading and writing to files Im talking about files that are
either packaged with the app when its uploaded and/or files that are created in the apps local folder at
runtime and then read from or written to. I havent yet tried going the file picker route,because I didnt
need (or want ) to give the user direct editing access to the files.
One of my apps works like this:
1.
2.
3.

It ships with a packaged text file thats read at runtime.


The user has the ability to add more entries to this data in an in-memory collection.
I want this data (both the original data and the user added stuff) to be persisted and available
when the user next runs the app.

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.

( * At some stage, Im going to make this smarter by using a background task, or a


service of some kind that will update this file. Im not there yet, but for sure Ill blog
about it once Ive got it sorted.)

My approach for accessing this file is as follows:


1. Create a variable to hold the text data in memory:
Dim TextData As String
2. Add an Imports statement for the Windows.Storage namespace

Imports Windows.Storage

3. Read the file and display the result


Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
' Calls method that Reads text from packaged file
TextData = Await ReadFromThePackagedFile("Assets\DefaultEntries.txt")

' For demo, display the result in a text block


tblkStoredData.Text = TextData
End Sub
Public Async Function ReadFromThePackagedFile(PackagedFileName As String) As
Task(Of String)
' Create a StorageFile to be used to access the text
Dim sampleFile As Windows.Storage.StorageFile = Nothing
' Define the location where file will have been installed
Dim package As Windows.ApplicationModel.Package =
Windows.ApplicationModel.Package.Current
Dim installedLocation As Windows.Storage.StorageFolder =
package.InstalledLocation
' Get the file
sampleFile = Await installedLocation.GetFileAsync(PackagedFileName)
' If file found, read aand return the contents; otherwise return a message
to inform the caller
If sampleFile IsNot Nothing Then
Dim fileContent As String = Await FileIO.ReadTextAsync(sampleFile)
Return fileContent
Else
Return "Packaged File not found"
End If
End Function

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:

I combine the two chunks of data.


This combined data is then written to a new file thats created at run time.
But and heres the key to success before a new file is created, a check is made to see if this
dynamically created file already exists.
If it does,then the data is written to the file. If it doesnt exist, then its created and the data is
written to the file.
Obviously this ensures that there is only one app-created file in existence which, in effect,
becomes the master file.

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

Public Async Sub WriteAppendedDataToFile(FileNameToUse As String, TextToWrite As


String)
' Find the local storage folder
Dim TheFolderName = Windows.Storage.ApplicationData.Current.LocalFolder
' Collision setting set to OpenIfExists to avoid multiple new files or loss
of previously saved data
Dim TheCollisionOption = Windows.Storage.CreationCollisionOption.OpenIfExists
' Create or open the file
Dim TheStorageFile = Await TheFolderName.CreateFileAsync(FileNameToUse,
TheCollisionOption)
' Write to the file
If TheStorageFile IsNot Nothing Then
Await Windows.Storage.FileIO.WriteTextAsync(TheStorageFile, TextToWrite)
End If
End Sub
As noted in the commenting, the key to this working is the OpenIfExists option. I think the default value is
GenerateUniqueName,which would result in multiple files being created. The other options are
FailIfExists, which you certainly wouldnt want nor the final option of ReplaceExisting.
Step 3 Checking that it works by reading the combined file
The code for reading from the local storage file is similar to that for writing. In fact, its identical in parts
and Id usually factor that out into a separate method that can be called by both these two. But for the
sake of this demo, Ive left the duplication in.

Private Async Sub Button_Click_2(sender As Object, e As RoutedEventArgs)


' Read the dynamically created file's content and display it
TextData = Await ReadFromFile("AmalgamatedData")
' Display for demo
tblkFinalResult.Text = TextData
End Sub
Public Async Function ReadFromFile(FileNameToUse As String) As Task(Of String)
' Find the local storage folder
Dim TheFolderName = Windows.Storage.ApplicationData.Current.LocalFolder
' Collisison setting set to OpenIfExists to avoid multiple new files or loss
of previously saved data
Dim TheCollisionOption = Windows.Storage.CreationCollisionOption.OpenIfExists
Dim TheStorageFile = Await TheFolderName.CreateFileAsync(FileNameToUse,
TheCollisionOption)
' Read the existing file, if it exists
If TheStorageFile IsNot Nothing Then
Dim AmalgamatedContent = Await
Windows.Storage.FileIO.ReadTextAsync(TheStorageFile)
Return AmalgamatedContent
Else : Return "Amalgamated storage file not found"
End If
End Function
Running this code in the same session will let you see that the amalgamated data is indeed now all saved
into the local storage file.
When the app is run again in a new session that is, the app is closed and then restarted from the Start
Screen - and the data is read from the combined data/local storage file, all of the combined data will be
there. And of course the user can add further text, save it to the combined file and it will be appended to
the end of the file, saved and be available for that session and any future ones. And do this over and

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

Acceder al sistema de archivos de manera


eficaz (XAML)
El sistema de archivos es un origen comn de problemas de rendimiento. El acceso a los
archivos puede consumir muchos recursos debido a la latencia del disco y a la memoria
y los ciclos de CPU necesarios para almacenar los datos. Cuando quieras acceder a una
coleccin grande de archivos y a valores de propiedad diferentes de las propiedades
tpicas Name, FileType y Path, para hacerlo, crea QueryOptions y llama a
SetPropertyPrefetch.
El mtodo SetPropertyPrefetch puede mejorar considerablemente el rendimiento de
las aplicaciones que muestran una coleccin de elementos obtenidos del sistema de
archivos, como una coleccin de imgenes. En los ejemplos siguientes se muestran
algunas maneras de acceder a varios archivos.
En el primer ejemplo se usa Windows.Storage.StorageFolder.GetFilesAsync para
recuperar informacin sobre el nombre de un conjunto de archivos. Con este enfoque se
logra un buen rendimiento, porque en el ejemplo solo se accede a la propiedad name.
C#
VB
Copiar
Dim library As StorageFolder = Windows.Storage.KnownFolders.PicturesLibrary
Dim files As IReadOnlyList(Of StorageFile) =
Await
library.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByDate)
For i As Integer = 0 To files.Count - 1
' do something with the name of each file
Dim fileName As String = files(i).Name
Next i

En el segundo ejemplo se usa Windows.Storage.StorageFolder.GetFilesAsync y


despus se recuperan las propiedades de la imagen para cada archivo. Con este enfoque
se logra un rendimiento deficiente.
C#
VB
Copiar
Dim library As StorageFolder = Windows.Storage.KnownFolders.PicturesLibrary
Dim files As IReadOnlyList(Of StorageFile) = Await
library.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByDate)
For i As Integer = 0 To files.Count - 1

Dim imgProps As ImageProperties =


Await files(i).Properties.GetImagePropertiesAsync()
' do something with the date the image was taken
Dim dateTaken As DateTimeOffset = imgProps.DateTaken
Next i

En el tercer ejemplo se usa QueryOptions para obtener informacin sobre un conjunto


de archivos. Con este enfoque se logra un rendimiento mucho mejor que en el ejemplo
anterior.
C#
VB
Copiar
' Set QueryOptions to prefetch our specific properties
Dim queryOptions = New
Windows.Storage.Search.QueryOptions(CommonFileQuery.OrderByDate, Nothing)
queryOptions.SetThumbnailPrefetch(ThumbnailMode.PicturesView,
100,
Windows.Storage.FileProperties.ThumbnailOptions.ReturnOnlyIfCached)
queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties,
New String() {"System.Size"})
Dim queryResults As StorageFileQueryResult =
KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions)
Dim files As IReadOnlyList(Of StorageFile) = Await
queryResults.GetFilesAsync()
For Each file In files
Dim imageProperties As ImageProperties = Await
file.Properties.GetImagePropertiesAsync()
' Do something with the date the image was taken.
Dim dateTaken As DateTimeOffset = imageProperties.DateTaken
' Performance gains increase with the number of properties that are
accessed.
Dim propertyResults As IDictionary(Of String, Object) =
Await file.Properties.RetrievePropertiesAsync(New String()
{"System.Size"})
' Get/Set extra properties here
Dim systemSize = propertyResults("System.Size")
Next file

Si realizas varias operaciones en objetos Windows.Storage, como


Windows.Storage.ApplicationData.Current.LocalFolder, crea una variable local
para hacer referencia a ese origen de almacenamiento de modo que no tengas que
recrear objetos intermedios cada vez que accedas a l.

Rendimiento de secuencias en C# y Visual Basic


Almacenar en bfer entre secuencias WinRT y .NET

En muchos escenarios, quizs quieras convertir una secuencia de Windows en tiempo


de ejecucin (como Windows.Storage.Streams.IInputStream o IOutputStream) en
una secuencia de .NET (System.IO.Stream). Por ejemplo, esto es til cuando escribes
una aplicacin de la Tienda Windows y quieres usar cdigo .NET existente que
funciona en secuencias con el sistema de archivos de Windows en tiempo de ejecucin.
Para ello, las API de .NET para aplicaciones de la Tienda Windows proporcionan
mtodos de extensin que te permiten convertir tipos de secuencias entre .NET y
Windows en tiempo de ejecucin. Para obtener ms informacin, consulta
WindowsRuntimeStreamExtensions.
Cuando conviertes una secuencia de Windows en tiempo de ejecucin en una secuencia
de .NET, creas efectivamente un adaptador para la secuencia subyacente de Windows
en tiempo de ejecucin. En algunas circunstancias, invocar mtodos en secuencias de
Windows en tiempo de ejecucin tiene asociado un costo. Esto puede afectar la
velocidad de la aplicacin, especialmente en escenarios donde realizas varias
operaciones pequeas y frecuentes de lectura o escritura.
Para aumentar la velocidad de la aplicacin, los adaptadores de secuencias de Windows
en tiempo de ejecucin contienen un bfer de datos. La siguiente muestra de cdigo
indica pequeas lecturas consecutivas usando un adaptador de secuencias de Windows
en tiempo de ejecucin con un tamao de bfer predeterminado.
C#
VB
Copiar
Dim file As StorageFile = Await Windows.Storage.ApplicationData.Current _
.LocalFolder.GetFileAsync("example.txt")
Dim windowsRuntimeStream As Windows.Storage.Streams.IInputStream =
Await file.OpenReadAsync()
Dim destinationArray() As Byte = New Byte(8) {}
' Create an adapter with the default buffer size.
Dim managedStream As Stream = windowsRuntimeStream.AsStreamForRead()
Using (managedStream)
' Read 8 bytes into destinationArray.
' A larger block is actually read from the underlying
' windowsRuntimeStream and buffered within the adapter.
Await managedStream.ReadAsync(destinationArray, 0, 8)
' Read 8 more bytes into destinationArray.
' This call may complete much faster than the first call
' because the data is buffered and no call to the
' underlying windowsRuntimeStream needs to be made.
Await managedStream.ReadAsync(destinationArray, 0, 8)
End Using

Este comportamiento de bfer es conveniente en la mayora de los escenarios en que se


convierte una secuencia de Windows en tiempo de ejecucin en una de .NET. Sin
embargo, en algunos escenarios quizs necesites ajustar el comportamiento de bfer
para aumentar el rendimiento.
Trabajar con grandes conjuntos de datos

Cuando leas o escribas grandes conjuntos de datos, podrs aumentar tu velocidad de


lectura o escritura al proporcionar un tamao de bfer ms grande a los mtodos de
extensin AsStreamForRead, AsStreamForWrite y AsStream. Esto le da al
adaptador de secuencias un bfer interno de mayor tamao. Por ejemplo, cuando se pasa
una secuencia de un archivo grande a un analizador XML, el analizador puede hacer
varias lecturas secuenciales pequeas de la secuencia. Un bfer grande puede reducir la
cantidad de llamadas a la secuencia de Windows en tiempo de ejecucin y aumentar el
rendimiento.
Nota Debes tener cuidado al configurar un tamao de bfer que sea mayor a 80 KB
aproximadamente, ya que esto puede causar la fragmentacin del montn del colector
de elementos no utilizados (consulta Mejorar el rendimiento de la recoleccin de
elementos no utilizados). El siguiente ejemplo de cdigo crea un adaptador de
secuencias administradas con un bfer de 81.920 bytes.
C#
VB
Copiar
' Create a stream adapter with an 80 KB buffer.
Dim managedStream As Stream = nativeStream.AsStreamForRead(bufferSize:=81920)

Los mtodos Stream.CopyTo y CopyToAsync tambin asignan un bfer local para


copiar entre secuencias. Al igual que con el mtodo de extensin AsStreamForRead,
podrs obtener un mejor rendimiento para copias de secuencias grandes al invalidar el
tamao de bfer predeterminado. El siguiente ejemplo de cdigo demuestra cmo
cambiar el tamao del bfer predeterminado de una llamada CopyToAsync.
C#
VB
Copiar
Dim destination As MemoryStream = New MemoryStream()
' copies the buffer into memory using the default copy buffer
Await managedStream.CopyToAsync(destination)
' Copy the buffer into memory using a 1 MB copy buffer.

Await managedStream.CopyToAsync(destination, bufferSize:=1024 * 1024)

Este ejemplo usa un bfer de 1 MB, que es mayor que el de 80 KB previamente


recomendado. El uso de este tamao de bfer puede mejorar el rendimiento de la
operacin de copia de varios conjuntos grandes de datos (es decir, varios cientos de
megabytes). Si embargo, este bfer se asigna al montn de objetos grandes y podra
degradar el rendimiento de la recoleccin de elementos no utilizados. Solo debes usar
tamaos ms grandes de bfer cuando mejoren notablemente el rendimiento de tu
aplicacin.
Cuando trabajas con una gran cantidad de secuencias al mismo tiempo, es posible que
quieras reducir o eliminar la sobrecarga de memoria del bfer. Puedes especificar un
bfer ms pequeo o establecer el parmetro bufferSize en 0 para desactivar el
almacenamiento en bfer por completo para ese adaptador de secuencias. An puedes
lograr un buen rendimiento sin el almacenamiento en bfer, si realizas lecturas o
escrituras grandes en la secuencia administrada.
Realizar operaciones sensibles a la latencia

Probablemente quieras evitar el almacenamiento en bfer, en el caso de escrituras y


lecturas de latencia baja y en el caso de que no quieras leer en bloques grandes de una
secuencia subyacente de Windows en tiempo de ejecucin. Por ejemplo, podras querer
escrituras y lecturas de latencia baja si ests usando la secuencia de comunicaciones de
red.
En una aplicacin de chat, podras usar una secuencia en una interfaz de red para enviar
y recibir mensajes. En este caso quieres enviar mensajes apenas estn listos, en lugar de
esperar que el bfer se rellene. Si estableces el tamao del bfer en 0 cuando llamas a
los mtodos de extensin AsStreamForRead, AsStreamForWrite y AsStream,
entonces el adaptador resultante no asignar un bfer y todas las llamadas manipularn
directamente la secuencia de Windows en tiempo de ejecucin.

Fuente: http://msdn.microsoft.com/es-es/library/windows/apps/hh994634.aspx

ApplicationData.LocalFolder | localFolder Property


Obtiene la carpeta raz del almacn de datos local de la aplicacin.

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="" />

Para tener acceso a archivos del paquete de la aplicacin, utilice


Windows.ApplicationModel.Package.Current.InstalledLocation.
Para solicitar que los datos de la aplicacin para la bsqueda estn indexados mediante
Windows, cree una carpeta denominada "Indexed" en esta carpeta y almacene los
archivos que desea indizar all. Windows indiza el contenido del archivo y los
metadatos (propiedades) en esta carpeta "Indexed" y todas sus subcarpetas.

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

Inicio rpido: datos de aplicaciones locales (HTML)


Idioma: HTML | XAML

Obtn informacin sobre el almacenamiento y la recuperacin de configuracin y


archivos desde el almacn de datos de aplicacin locales.
Obtener los contenedores para los archivos y la configuracin de la aplicacin

Usa la propiedad ApplicationData.localSettings para obtener la configuracin en un


objeto ApplicationDataContainer. Usa la propiedad ApplicationData.localFolder
para obtener los archivos en un objeto StorageFolder.
JavaScript
Copiar
var localSettings = applicationData.localSettings;
var localFolder = applicationData.localFolder;

En los siguientes pasos se usan las variables localSettings y localFolder de este


paso.
Escribir datos en una configuracin

Usa la propiedad ApplicationDataContainer.values para obtener acceso a la


configuracin en el contenedor localSettings que obtuvimos en el paso anterior. En
este ejemplo se crea una configuracin llamada exampleSetting.
JavaScript
Copiar
// Simple setting
localSettings.values["exampleSetting"] = "Hello Windows";

Un objeto ApplicationDataCompositeValue contiene configuraciones a las que debe


obtenerse acceso de forma atmica. En este ejemplo se crea una configuracin
compuesta llamada exampleCompositeSetting y se la agrega al contenedor
localSettings.
JavaScript
Copiar

// Composite setting
var composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";
localSettings.values["exampleCompositeSetting"] = composite;

Llama al mtodo ApplicationDataContainer.CreateContainer para crear un


contenedor de configuraciones. En este ejemplo se crea un contenedor de
configuraciones denominado exampleContainer y se agrega una configuracin
llamada exampleSetting. El valor Always de la enumeracin
ApplicationDataCreateDisposition indica que el contenedor se crea si no existe ya.
JavaScript
Copiar
// Setting in a container
var container = localSettings.createContainer("exampleContainer",
Windows.Storage.ApplicationDataCreateDisposition.always);
if (localSettings.containers.hasKey("exampleContainer"))
{
localSettings.containers.lookup("exampleContainer").values["exampleSetting"] =
"Hello Windows";
}

Leer datos desde una configuracin

Usa la propiedad ApplicationDataContainer.values para obtener acceso a la


configuracin exampleSetting en el contenedor localSettings.
JavaScript
Copiar
// Simple setting
var value = localSettings.values["exampleSetting"];
if (!value)
{
// No data
}
else
{
// Access data in value
}

Usa la propiedad ApplicationDataContainer.values para obtener acceso a la


configuracin exampleCompositeSetting en el contenedor localSettings.

JavaScript
Copiar
// Composite setting
var composite = localSettings.values["exampleCompositeSetting"];
if (!composite)
{
// No data
}
else
{
// Access data in composite["intVal"] and composite["strVal"]
}

Usa la propiedad ApplicationDataContainer.values para obtener acceso a la


configuracin exampleSetting en el contenedor exampleContainer.
JavaScript
Copiar
// Setting in a container
var hasContainer = localSettings.containers.hasKey("exampleContainer");
if (hasContainer)
{
// Access data in
localSettings.containers.lookup("exampleContainer").values.hasKey("exampleSett
ing");
}

Escribir datos en un archivo

Usa las API de archivo, como Windows.Storage.StorageFolder.createFileAsync y


Windows.Storage.FileIO.writeTextAsync, para crear y actualizar un archivo en el
almacn de datos de aplicacin local. En este ejemplo se crea un archivo llamado
dataFile.txt en el contenedor localFolder y se escriben la fecha y la hora actuales
en el archivo. El valor replaceExisting de la enumeracin CreationCollisionOption
indica que se reemplace el archivo si ya existe.
JavaScript
Copiar
function writeTimestamp() {
localFolder.createFileAsync("dataFile.txt",
Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (sampleFile) {
var formatter = new
Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
var timestamp = formatter.format(new Date());

return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);


}).done(function () {
});
}

Leer datos desde un archivo

Usa las API de archivo, como Windows.Storage.StorageFolder.getFileAsync,


Windows.Storage.StorageFile.GetFileFromApplicationUriAsync y
Windows.Storage.FileIO.readTextAsync para abrir y leer un archivo en el almacn de
datos de la aplicacin local. En este ejemplo se abre el archivo dataFile.txt creado en
el paso anterior y se lee la fecha en l. El valor openIfExists de la enumeracin
CreationCollisionOption indica que el archivo debe existir. Para obtener informacin
detallada sobre la carga de recursos de archivos de varias ubicaciones, consulta Cmo
cargar recursos de archivos.
JavaScript
Copiar
function readTimestamp() {
localFolder.getFileAsync("dataFile.txt")
.then(function (sampleFile) {
return Windows.Storage.FileIO.readTextAsync(sampleFile);
}).done(function (timestamp) {
// Data is contained in timestamp
}, function () {
// Timestamp not found
});
}

Eliminar configuraciones cuando se termine con ellas

Llama al mtodo ApplicationDataContainerSettings.remove para eliminar la


configuracin exampleSetting cuando hayas terminado.
JavaScript
Copiar
// Simple setting
localSettings.values.remove("exampleSetting");

Llama al mtodo ApplicationDataCompositeValue.remove para eliminar la


configuracin compuesta exampleCompositeSetting cuando hayas terminado.
JavaScript
Copiar

// Delete composite setting


localSettings.values.remove("exampleCompositeSetting");

Llama al mtodo ApplicationDataContainer.deleteContainer para eliminar el


contenedor de configuraciones exampleContainer cuando hayas terminado.
JavaScript
Copiar
// Delete container
localSettings.deleteContainer("exampleContainer");

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

Inicio rpido: datos de aplicaciones locales (XAML)


Idioma: HTML | XAML

Obtn informacin sobre cmo almacenar y recuperar configuraciones y archivos desde


el almacn de datos de aplicaciones locales.
Gua bsica: Relacin de este tema con los dems. Consulta:

Gua bsica para crear aplicaciones de Windows en tiempo de ejecucin con C# o


Visual Basic
Gua bsica para crear aplicaciones de Windows en tiempo de ejecucin con C++

Obtener los contenedores para los archivos y la configuracin de la aplicacin

Usa la propiedad ApplicationData.LocalSettings para obtener la configuracin en un


objeto ApplicationDataContainer. Usa la propiedad ApplicationData.LocalFolder
para obtener los archivos en un objeto StorageFolder.
C#
C++
VB
Copiar
Dim localSettings As Windows.Storage.ApplicationDataContainer =
Windows.Storage.ApplicationData.Current.LocalSettings
Dim localFolder As Windows.Storage.StorageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder

En las siguientes secciones se usan las variables localSettings y localFolder de


esta seccin.
Escribir datos en una configuracin

Usa la propiedad ApplicationDataContainer.Values para obtener acceso a la


configuracin en el contenedor localSettings que obtuvimos en el paso anterior. En
este ejemplo se crea una configuracin llamada exampleSetting.
C#
C++
VB
Copiar

' Simple setting


localSettings.Values("exampleSetting") = "Hello Windows";

Un objeto ApplicationDataCompositeValue contiene configuraciones a las que debe


obtenerse acceso de forma atmica. En este ejemplo se crea una configuracin
compuesta llamada exampleCompositeSetting y se la agrega al contenedor
localSettings.
C#
C++
VB
Copiar
' Composite setting
Dim composite As New Windows.Storage.ApplicationDataCompositeValue
composite("intVal") = 1
composite("strVal") = "string";
localSettings.Values("exampleCompositeSetting") = composite

Llama al mtodo ApplicationDataContainer.CreateContainer para crear un


contenedor de configuraciones. En este ejemplo se crea un contenedor de
configuraciones denominado exampleContainer y se agrega una configuracin
llamada exampleSetting. El valor Always de la enumeracin
ApplicationDataCreateDisposition indica que el contenedor se crea si no existe ya.
C#
C++
VB
Copiar
' Setting in a container
Dim container As Windows.Storage.ApplicationDataContainer =
localSettings.CreateContainer("exampleContainer",
Windows.Storage.ApplicationDataCreateDisposition.Always)
If localSettings.Containers.ContainsKey("exampleContainer") Then
localSettings.Containers("exampleContainer").Values("exampleSetting") =
"Hello Windows"
End If

Leer datos desde una configuracin

Usa la propiedad ApplicationDataContainer.Values para obtener acceso a la


configuracin exampleSetting en el contenedor localSettings.
C#
C++
VB
Copiar
' Simple setting
Dim value As Object = localSettings.Values("exampleSetting")

Usa la propiedad ApplicationDataContainer.Values para obtener acceso a la


configuracin exampleCompositeSetting en el contenedor localSettings.
C#
C++
VB
Copiar
' Composite setting
Dim composite As Windows.Storage.ApplicationDataCompositeValue =
CType(localSettings.Values("exampleCompositeSetting"),
Windows.Storage.ApplicationDataCompositeValue)
If composite Is Nothing Then
' No data
Else
' Access data in composite("intVal") and composite("strVal")
End If

Usa la propiedad ApplicationDataContainer.Values para obtener acceso a la


configuracin exampleSetting en el contenedor exampleContainer.
C#
C++
VB
Copiar
' Setting in a container

Dim hasContainer As Boolean =


localSettings.Containers.ContainsKey("exampleContainer")
Dim hasSetting As Boolean = False
If hasContainer Then
hasSetting =
localSettings.Containers("exampleContainer").Values.ContainsKey("exampleSettin
g")
End If

Escribir datos en un archivo

Usa las API de archivo, como Windows.Storage.StorageFolder.CreateFileAsync y


Windows.Storage.FileIO.WriteTextAsync, para crear y actualizar un archivo en el
almacn de datos de aplicacin local. En este ejemplo se crea un archivo llamado
dataFile.txt en el contenedor localFolder y se escriben la fecha y la hora actuales
en el archivo. El valor ReplaceExisting de la enumeracin CreationCollisionOption
indica que se reemplace el archivo si ya existe.

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

Leer datos desde un archivo

Usa las API de archivo, como Windows.Storage.StorageFolder.GetFileAsync,


Windows.Storage.StorageFile.GetFileFromApplicationUriAsync y
Windows.Storage.FileIO.ReadTextAsync para abrir y leer un archivo en el almacn
de datos de la aplicacin local. En este ejemplo se abre el archivo dataFile.txt creado
en el paso anterior y se lee la fecha en l. Para obtener informacin detallada sobre la

carga de recursos de archivos de varias ubicaciones, consulta Cmo cargar recursos de


archivos.
C#
C++
VB
Copiar
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

Eliminar configuraciones cuando se termine con ellas

Llama al mtodo ApplicationDataContainerSettings.Remove para eliminar la


configuracin exampleSetting cuando hayas terminado.
C#
C++
VB
Copiar
localSettings.Values.Remove("exampleSetting")

Llama al mtodo ApplicationDataCompositeValue.Remove para eliminar la


configuracin compuesta exampleCompositeSetting cuando hayas terminado.
C#
C++
VB
Copiar
localSettings.Values.Remove("exampleCompositeSetting")

Llama al mtodo ApplicationDataContainer.DeleteContainer para eliminar el


contenedor de configuraciones exampleContainer cuando hayas terminado.
C#
C++
VB
Copiar
localSettings.DeleteContainer("exampleContainer")

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

Informacin general de .NET para aplicaciones de la Tienda


Windows
Este tema an no ha recibido ninguna valoracin - Valorar este tema

.NET Framework proporciona un subconjunto de tipos administrados que puedes usar


para crear aplicaciones de la Tienda Windows con C# o Visual Basic. Este subconjunto
de tipos administrados se denomina .NET para aplicaciones de la Tienda Windows y
permite a los desarrolladores de .NET Framework crear aplicaciones de la Tienda
Windows dentro en un marco de programacin que resulta familiar. Los tipos que no
estn relacionados con el desarrollo de aplicaciones de la Tienda Windows no se
incluyen en el subconjunto.
Estos tipos administrados se usan con tipos de la API de Windows en tiempo de
ejecucin para crear aplicaciones de la Tienda Windows. Por lo general, no notars
diferencia alguna entre el uso de los tipos administrados y de los tipos de Windows en
tiempo de ejecucin, salvo que los tipos administrados residen en los espacios de
nombres que comienzan con System y los tipos de Windows en tiempo de ejecucin
residen en los espacios de nombres que comienzan con Windows. En combinacin,
.NET para aplicaciones de la Tienda Windows y Windows en tiempo de ejecucin
proporcionan el conjunto completo de tipos y miembros disponibles para desarrollar
aplicaciones de la Tienda Windows con C# o Visual Basic.
El subconjunto de tipos administrados y miembros se dise con un claro objetivo
orientado al desarrollo de la aplicacin de la Tienda Windows. Como resultado, se
omite lo siguiente:

Los tipos y miembros que no son aplicables para desarrollar aplicaciones de la


Tienda Windows (como la consola y los tipos de ASP.NET).
Tipos obsoletos y heredados.
Tipos que se superponen con los tipos de Windows en tiempo de ejecucin.
Tipos y miembros que contienen funciones del sistema operativo (como
System.Diagnostics.EventLog y contadores de rendimiento).
Miembros que llevan a confusin (como el mtodo de Close en tipos de E/S).

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

espacios de nombres combinados que ofrece .NET para aplicaciones de la Tienda


Windows y Windows en tiempo de ejecucin (agrupados por rea funcional), consulta
la seccin .NET Framework y espacios de nombres de Windows en tiempo de
ejecucin.
Para obtener una lista de espacios de nombres y tipos incluidos en el subconjunto de
.NET Framework, consulta API de .NET para aplicaciones de la Tienda Windows.
Tambin puedes crear un proyecto de Biblioteca de clases portable para desarrollar una
biblioteca de .NET Framework que se pueda usar desde una aplicacin de la Tienda
Windows. El proyecto debe incluir .NET para aplicaciones de la Tienda Windows como
una de las plataformas de destino. Biblioteca de clases portable es especialmente til
cuando se quieren desarrollar clases que se puedan usar desde aplicaciones para
diferentes tipos de plataformas, como una aplicacin de Windows Phone, una aplicacin
de escritorio y una aplicacin de la Tienda Windows. Consulta Desarrollo
multiplataforma con .NET Framework.
En este tema, se incluyen las siguientes secciones:

Convertir el cdigo existente de .NET Framework


Mtodos de extensin para convertir tipos
Espacios de nombres de .NET Framework y de Windows en tiempo de
ejecucin

Convertir el cdigo existente de .NET Framework

Por lo general, no solo cuando se convierte una aplicacin existente de .NET


Framework a una aplicacin de la Tienda Windows, se redisea la aplicacin de .NET
Framework para que el usuario disfrute de una experiencia nueva. Sin embargo, puede
que quieras convertir partes de una aplicacin existente de .NET Framework para su uso
en una aplicacin de la Tienda Windows. Cuando conviertas cdigo existente de .NET
Framework, debes estar al tanto de los siguientes cambios que es posible que debas
efectuar en la aplicacin de la Tienda Windows:

Cambios en la interfaz de usuario


Cambios de E/S
Cambios de almacenamiento
Cambios de red
Cambios de subprocesos
Cambios de reflexin
Cambios de seguridad
Cambios de recursos
Cambios de excepcin
Cambios de la WCF
Cambios en los tipos generales de .NET Framework

Cambios en la interfaz de usuario

Cuando conviertas cdigo de interfaz de usuario desde una aplicacin basada en


Silverlight o desde una aplicacin de Windows Phone, puedes usar muchos de los
mismos tipos de la interfaz de usuario, pero los tipos se encuentran ahora en los
espacios de nombres Windows.UI.Xaml en lugar de en los espacios de nombres
System.Windows. Estos nuevos tipos de interfaz de usuario son similares a los tipos
anteriores de la interfaz de usuario de .NET Framework, pero contienen algunos
miembros diferentes.
Cambia
Tipos de interfaz de usuario en el
espacio de nombres
System.Windows.*

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)

Para obtener ms informacin sobre cmo migrar cdigo de interfaz de usuario,


consulta Migrar una aplicacin de Windows Phone 7 a XAML.
Cambios de E/S

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

Mtodo Close() en clases de


E/S

Declara y crea una instancia del objeto de E/S dentro de


una instruccin using (C#) o Using (Visual Basic) para
asegurarte de que se desecha correctamente; por
ejemplo:
C#
VB
Copiar

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 =

Cdigo para recuperar y abrir


un archivo

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

En lugar de usar la clase System.IO.IsolatedStorage, usa los tipos en los espacios de


nombres Windows.Storage para almacenar datos locales y archivos.
Cambia

Por
La propiedad LocalFolder de la clase
Windows.Storage.ApplicationData

Clase
System.IO.IsolatedStorage.IsolatedStorageFile Copiar
ApplicationData.Current.LocalFolder

La propiedad LocalSettings de la clase


Windows.Storage.ApplicationData

Clase
System.IO.IsolatedStorage.IsolatedStorageSetti Copiar
ngs

ApplicationData.Current.LocalSettin
gs

Para obtener ms informacin, consulta Datos de la aplicacin.

Cambios de red

Cambia

Clase System.Net.WebClient

Tipos en el espacio de nombres


System.Net.Sockets

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

Identificadores URI relativos,


cuando se pasan a los tipos de
Para obtener ms informacin, consulta Pasar un URI
Windows en tiempo de ejecucin
a Windows en tiempo de ejecucin.
Cdigo de control de
excepciones que detecta la
Cdigo que detecta la excepcin de FormatException,
excepcin de
que es la clase primaria de UriFormatException
UriFormatException
Cambios de subprocesos

Algunos de los miembros de subprocesos de .NET Framework han cambiado y ahora se


encuentran disponibles algunos en la API de Windows en tiempo de ejecucin.
Cambia

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#

Cdigo que pone en cola trabajos para el


grupo

VB
Copiar

Task.Run(
Sub()
' work goes here
End Sub)

C#
VB

Cdigo que pone en cola trabajo para el


grupo y espera a que finalice

Copiar
Await Task.Run(
Sub()
' work goes here
End Sub)

C#
VB

Cdigo que crea un elemento de trabajo de Copiar


ejecucin prolongada

Task.Factory.StartNew(
Sub()
' work goes here
End Sub,
TaskCreationOptions.LongRunning)

Cambios de reflexin

La mayora de los miembros de la clase System.Type se han movido a la clase


System.Reflection.TypeInfo. Puedes recuperar el objeto TypeInfo llamando al mtodo
System.Reflection.IntrospectionExtensions.GetTypeInfo(System.Type), que es un
mtodo de extensin para Type.
Cambia
type.Assembly
type.GetMethods(BindingFlags.Declar
edOnly)
type.GetMethod("MethodName",
BindingFlags.DeclaredOnly)
type.GetNestedTypes()
Mtodo
System.Delegate.CreateDelegate

Por
type.GetTypeInfo().Assembly
type.GetTypeInfo().DeclaredMethods
type.GetTypeInfo().GetDeclaredMethod("Meth
odName")
type.GetTypeInfo().DeclaredNestedTypes
Mtodo MethodInfo.CreateDelegate

Para obtener ms informacin, consulta Reflexin en .NET Framework para


aplicaciones de la Tienda Windows en MSDN Library.
Cambios de seguridad

Muchos de los tipos de seguridad, la autenticacin y las operaciones criptogrficas estn


disponibles a travs de los tipos de Windows en tiempo de ejecucin. Para obtener una
lista completa de los espacios de nombres de seguridad que estn disponibles para las
aplicaciones de la Tienda Windows, consulta la lista de espacios de nombres de
seguridad ms adelante en este tema.

Cambios de recursos

Para las aplicaciones de la Tienda Windows, se crea un nico archivo de recursos en


lugar del modelo de concentrador y radio que se usa en aplicaciones de escritorio.
Adems, puedes usar los tipos de recursos de los espacios de nombres
Windows.ApplicationModel.Resources y Windows.ApplicationModel.Resources.Core
en lugar del espacio de nombres System.Resources.
Para obtener ms informacin, consulta Crear y recuperar recursos en aplicaciones de
Windows Store.
Cambios de excepcin

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

En las aplicaciones de la Tienda Windows, puedes utilizar la funcionalidad de cliente de


Windows Communication Foundation (WCF) para recuperar datos de un servicio WCF,
pero no puedes crear un servicio WCF para servir datos.
Cambios en los tipos generales de .NET Framework

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)

Mtodos de extensin para convertir tipos

En la mayora de los casos, se desarrollan aplicaciones de la Tienda Windows con tipos


de .NET Framework y tipos de Windows en tiempo de ejecucin en combinacin sin
ninguna consideracin o conversin especiales. Sin embargo, en algunos casos, .NET
Framework aporta mtodos de extensin para simplificar la interaccin entre los tipos
de .NET Framework y tipos de Windows en tiempo de ejecucin. Estos mtodos de
extensin estn en las clases siguientes:

System.IO.WindowsRuntimeStreamExtensions : para convertir entre secuencias


administradas y secuencias en Windows en tiempo de ejecucin.
System.IO.WindowsRuntimeStorageExtensions : para abrir archivos y carpetas
de Windows en tiempo de ejecucin como secuencias administradas.
System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExt
ensions : para conversiones a IBuffer y desde IBuffer.

.NET Framework y espacios de nombres Windows en tiempo de


ejecucin

En las secciones siguientes se enumeran los espacios de nombres que se proporcionan


en .NET para aplicaciones de la Tienda Windows y Windows en tiempo de ejecucin,
organizados segn su funcionalidad.
Colecciones

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

Managed Extensibility Framework (MEF)

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

Automatizacin de la interfaz de usuario

Windows.UI.Xaml.Automation
Windows.UI.Xaml.Automation.Peers

Windows.UI.Xaml.Automation.Provider
Windows.UI.Xaml.Automation.Text

Interaccin del usuario

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

Potrebbero piacerti anche