יום שני, 2 ביוני 2014

המרת משתנים ב-c#-win8

Index:
-   String to byte[]
-   Byte[] to string

-   Covert File to Byte Array
-   Save A File
-   bytes[] to filestream
    
-   Get thumbnail from video / image
-   ImageSource To BitmapImage
-   Byte[] to bitmap
-   Byte[] to Stream
-   stream to byte[]

-    stream to IrandomAccessStream
-    IRandomAccessStream to stream
-   Buffer to stream
-   stream to buffer
-   Byte[] to InMemoryRandomAccessStream or IRandomAccessStream
-   Conversion between IRandomAccessStream and FileInputStream/FileOutputStream
-   Byte[] to InMemoryRandomAccessStream or IRandomAccessStream
-   Write a file using StreamWriter
    
-   Path to StorageFile
-   Get file to storageFile
-   Get a file from media folder to a StorageFile var
-   Storagefile to string
-   byte[] to storagefile
-   StorageFile to Byte[]
-   Storagefile to IRandomAccessStream , to ImageSource (bitmap)
    
-   IRandomAccessStream to byte[]

-   Binary To String To Binary



Refreshing a page
var _Frame = Window.Current.Content as Frame;
_Frame.Navigate(_Frame.Content.GetType());
_Frame.GoBack(); // remove from BackStack

string to byte[]
string str = System.Text.Encoding.UTF8.GetString(byte_array, 0, byte_array.Length);

string to Byte[]
static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

byte[] StringToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}

byte[] to string
string str = "This is the string to be converted";
byte[] buffer = Encoding.ASCII.GetBytes(str);


Byte[] to string
static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}

Covert File to Byte Array
 private async Task<byte[]> ConvertImagetoByte(StorageFileimage)
{
    
IRandomAccessStream fileStream = awaitimage.OpenAsync(FileAccessMode.Read);
    
var reader =
       
new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
    
await reader.LoadAsync((uint)fileStream.Size);
    
byte[] pixels = new byte[fileStream.Size];
    reader.ReadBytes(pixels);
    
return pixels;
}
Save File (byte[], filepath)
public static async Task<StorageFile> SaveFile(byte[] b, string filepath)
{
            string folder = filepath.Substring(0, filepath.LastIndexOf('\\'));
            string filename = filepath.Substring(filepath.LastIndexOf('\\'));

            StorageFile sf = await (await StorageFolder.GetFolderFromPathAsync(folder))
.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream fileStream = await sf.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (DataWriter dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteBytes(b);
                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }
                    await outputStream.FlushAsync();
                }
                await fileStream.FlushAsync();
            }
            return sf;
}


//bytes[] -to- filestream
await stream.WriteAsync(bytes.AsBuffer());
Get thumbnail from video / image
Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
Windows.Storage.FileProperties.StorageItemThumbnail thumbnail =
        await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapimage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

bitmapimage.SetSource(thumbnail);
return bitmapimage;

ImageSource To BitmapImage
//image source to bitmapmimage
BitmapImage bi = _imgsrc as BitmapImage;

Byte[] to bitmap
public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
    MemoryStream stream = new MemoryStream(byteArray);
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource((IRandomAccessStream)stream);
    return bitmapImage;
}

Byte[] to Stream
Stream stream = new MemoryStream(byteArray);


stream to byte[]
public static byte[] ConvertStreamToByteArray(Stream inputstream)
//in use with decrypt
{
    byte[] data;
    using (var br = new BinaryReader(inputstream))
           data = br.ReadBytes((int)inputstream.Length);
    return data;
}


stream to byte[]
public static byte[] ToByteArray(this Stream stream)
{
  using (stream)
  {
      using (MemoryStream memStream = new MemoryStream())
      {
          stream.CopyTo(memStream);
          return memStream.ToArray();
      }
  }
}


stream to IRandomAccessStream
// stream to IRandomAccessStream 
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);

await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream);

IRandomAccessStream to stream
// IRandomAccessStream to stream

Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0));

Buffer to stream
// buffer to stream
Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer);

stream to buffer
// stream to buffer
MemoryStream memoryStream = new MemoryStream();          
 if (stream != null)
 {
      byte[] bytes = ReadFully(stream);
      if (bytes != null)
      {
           var binaryWriter = new BinaryWriter(memoryStream);
           binaryWriter.Write(bytes);
       }
  }

IBuffer buffer=WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream,0,(int)memoryStream.Length);


Byte[] to InMemoryRandomAccessStream or IRandomAccessStream
Add the using statement at the top of the document.
using System.Runtime.InteropServices.WindowsRuntime;
internal static async Task<InMemoryRandomAccessStream> ConvertTo(byte[] arr)
{
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await randomAccessStream.WriteAsync(arr.AsBuffer());
    stream.Seek(0); // Just to be sure.
                    // I don't think you need to flush here, but if it doesn't work, give it a try.
    return randomAccessStream;
}

Conversion between IRandomAccessStream and FileInputStream/FileOutputStream
//Conversion between IRandomAccessStream and FileInputStream/FileOutputStream
FileInputStream inputStream = randomStream.GetInputStreamAt(0) as FileInputStream;
FileOutputStream outStream = randomStream.GetOutputStreamAt(0) as FileOutputStream;



Write a file using StreamWriter in Win8
Instead of StreamWriter you would use something like this:
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync();

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
    {
        using (DataWriter dataWriter = new DataWriter(outputStream))
        {
            //TODO: Replace "Bytes" with the type you want to write.
            dataWriter.WriteBytes(bytes);
            await dataWriter.StoreAsync();
            dataWriter.DetachStream();
        }

        await outputStream.FlushAsync();
    }
}
You can look at the StringIOExtensions class in the WinRTXamlToolkit library for sample use.
EDIT*

While all the above should work - they were written before the FileIO class became available in WinRT, which simplifies most of the common scenarios that the above solution solves since you can now just call await FileIO.WriteTextAsync(file, contents) to write text into file and there are also similar methods to read, write or append strings, bytes, lists of strings or IBuffers.




Path to StorageFile
StorageFile sf = await StorageFile.GetFileFromPathAsync(filePath);

Get file to storageFile
StorageFile file = null;

 try
 {
    file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
}
catch (FileNotFoundException) { }


Get a file from media folder to a StorageFile var
private static async Task<StorageFile> DecryptImage(string filename) //,StorageFolder folder)
{
    StorageFolder appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    StorageFolder internalFolder = await appFolder.CreateFolderAsync
        "Media Files", CreationCollisionOption.OpenIfExists);
    StorageFile file = await internalFolder.GetFileAsync(filename);
    return file;
}


Storagefile to string
StorageFile sf = await StorageFile.GetFileFromPathAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\file.txt");
byte[] b = await Conversions.Convert_StorageFileToByteArray_Async(sf);
string password = Encoding.UTF8.GetString(b, 0, b.Length);



byte[] to storagefile
private static async Task<StorageFile> ByteArrayToStorageFile(byte[] data_bytes, string fileName)
{
    //creates an empty file, named by the 'filename' var
    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName,
CreationCollisionOption.ReplaceExisting);
    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
        {
            using (DataWriter dataWriter = new DataWriter(outputStream))
            {
                dataWriter.WriteBytes(data_byte);
                await dataWriter.StoreAsync();
                dataWriter.DetachStream();
            }
    // write data on the empty file:
            await outputStream.FlushAsync();
        }
        await fileStream.FlushAsync();
    }
}


StorageFile to Byte[]
private static async Task<Byte[]> ToByteArrayAsync(StorageFile storagefile)
//snir: storage ile to Byte[]
{
    using (IRandomAccessStream stream = await storagefile.OpenReadAsync())
    {
         using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
         {
              await reader.LoadAsync((uint)stream.Size);
              Byte[] bytes = new Byte[stream.Size];
              reader.ReadBytes(bytes);
              return bytes;
         }
    }

}

Storagefile to IRandomAccessStream , to ImageSource (bitmap)

private static async Task<ImageSource> Storagefile_To_IRAStream_To_Bitmap(string filepath)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IRandomAccessStream filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapimage = new BitmapImage();
bitmapimage.SetSource(filestream);
//filestream.Dispose();
return bitmapimage;
}


IRandomAccessStream to byte[]
here is using IBuffer (you must add System.Runtime.InteropServices.WindowsRuntime and System.IO namespaces)
// This is where the byteArray to be stored.
var bytes = new byte[myMemoryStream.Size];

// This returns IAsyncOperationWithProgess, so you can add additional progress handling
await myMemoryStream.ReadAsync(bytes.AsBuffer(), (uint)myMemoryStream.Size, Windows.Storage.Streams.InputStreamOptions.None);
here is the code to convert with data reader:
var reader = new DataReader(myMemoryStream.GetInputStreamAt(0));
var bytes  = new byte[myMemoryStream.Size];
await reader.LoadAsync((uint)myMemoryStream.Size);
reader.ReadBytes(bytes);


Binary To String / To Binary
CryptographicBuffer .
ConvertBinaryToString
ConvertStringToBinary

אין תגובות:

הוסף רשומת תגובה