Read() public méthode

public Read ( byte buffer, int offset, int count ) : int
buffer byte
offset int
count int
Résultat int
Exemple #1
0
 /// <summary>
 /// 读取本地文件信息,SilverLight缓存中
 /// </summary>
 /// <param name="rFileName">存储文件名</param>
 /// <returns>返回文件数据</returns>
 public static byte[] ReadSlByteFile(string rFileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
     System.IO.Stream stream = null;
     byte[]           buffer = null;
     try
     {
         isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
         if (!isf.FileExists(rFileName))
         {
             return(null);
         }
         stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, isf);
         buffer = new byte[stream.Length];
         stream.Read(buffer, 0, (int)stream.Length);
     }
     finally
     {
         if (stream != null)
         {
             stream.Close(); // Close the stream
             stream.Dispose();
         }
         isf.Dispose();
     }
     return(buffer);
 }
Exemple #2
0
        public override object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            _values = values;
            if (values.Any(w => w == null || string.IsNullOrEmpty(w.ToString())))
                return null;

            byte[] imageBytes;
            var path = string.Concat("/Shared/ShellContent/", string.Format("{0}.jpg", string.Join("_", values)));

            using (var iso = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!iso.FileExists(path))
                    return null;

                using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, iso))
                {
                    imageBytes = new byte[fileStream.Length];

                    fileStream.Read(imageBytes, 0, imageBytes.Length);
                }
            }

            using (var memoryStream = new MemoryStream(imageBytes))
            {
                BitmapImage bitmapImage = new BitmapImage();

                bitmapImage.SetSource(memoryStream);
                return bitmapImage;
            }
        }
Exemple #3
0
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            List<Run> runList = new List<Run>();
            string time, dist;

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("SavedSessions.txt", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
            {
                if (!stream.CanRead) return;

                long length = stream.Length;
                byte[] decoded = new byte[length];
                stream.Read(decoded, 0, (int)length);

                string str = "";
                for (int i = 0; i < decoded.Length; i++)
                    str += (char)decoded[i];

                string[] val = Regex.Split(str, " ");

                time = val[0] + ":" + val[1] + ":" + val[2] + val[3];
                dist = val[4];

                runList.Add(new Run(time, dist));
            }

            TransactionList.ItemsSource = runList;
        }
        //send song data over the socket
        //this uses an app specific socket protocol: send title, artist, then song data
        public async Task<bool> SendSongOverSocket(StreamSocket socket, string fileName, string songTitle, string songFileSize)
        {
            try
            {
                // Create DataWriter for writing to peer.
                _dataWriter = new DataWriter(socket.OutputStream);

                //send song title
                await SendStringOverSocket(songTitle);

                //send song file size
                await SendStringOverSocket(songFileSize);

                // read song from Isolated Storage and send it
                using (var fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    int readCount = 0;
                    _length = fileStream.Length;

                    //Initialize the User Interface elements
                    InitializeUI(fileName);

                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        readCount += bytesRead;
                        //UpdateUI
                        UpdateProgressBar(readCount);
                        //size of the packet
                        _dataWriter.WriteInt32(bytesRead);
                        //packet data sent
                        _dataWriter.WriteBytes(buffer);
                        try
                        {
                            await _dataWriter.StoreAsync();
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }
                    }
                }

                return true;
            }
            catch
            {
                return false;
            }

        }
 /// <summary>
 /// Reads all byte content from an isolated storage file.
 /// </summary>
 /// <param name="path">Path to the file.</param>
 /// <returns>The bytes read from the file.</returns>
 public static byte[] ReadBytesFromIsolatedStorage(string path)
 {
     // Access the file in the application's isolated storage.
     using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, file))
         {
             byte[] valueArray = new byte[readstream.Length];
             readstream.Read(valueArray, 0, valueArray.Length);
             return valueArray;
         }
     }
 }
        public static byte[] GetSubscriptionCertificate(string subscriptionId)
        {
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            byte[] certificateBytes = null;

            // Go into the isolated storage and retrieve the certificate.
            //
            using (var isoFileStream = new IsolatedStorageFileStream(subscriptionId + "\\management.cer", FileMode.Open, myStore))
            {
                certificateBytes = new byte[isoFileStream.Length];
                isoFileStream.Read(certificateBytes, 0, (int)isoFileStream.Length);
            }

            return certificateBytes;
        }
Exemple #7
0
 public static string ReadFile(string filename)
 {
     using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
     {
         try
         {
             IsolatedStorageFileStream filestream = new IsolatedStorageFileStream(filename, System.IO.FileMode.Open, isf);
             byte[] buffer = new byte[filestream.Length];
             filestream.Read(buffer,0,buffer.Length);
             string data = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
             return data;
         }
         catch (System.IO.FileNotFoundException)
         {
             return string.Empty;
         }
     }
 }
Exemple #8
0
        public static byte[] GetRecordByteArray(string name)
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

            MemoryStream stream = new MemoryStream();
            using (IsolatedStorageFileStream fStream = new IsolatedStorageFileStream("Music/" + name,
                FileMode.Open, file))
            {
                byte[] readBuffer = new byte[4096];
                int bytesRead = 0;

                while ((bytesRead = fStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    stream.Write(readBuffer, 0, bytesRead);
                }
            }

            return stream.ToArray();
        }
Exemple #9
0
        /// <summary>
        /// 获取上传进度记录
        /// </summary>
        /// <param name="key">记录文件名</param>
        /// <returns>上传进度数据</returns>
        public byte[] get(string key)
        {
            byte[] data = null;
            string filePath = Path.Combine(this.dir, StringUtils.urlSafeBase64Encode(key));
            try
            {
                using (IsolatedStorageFileStream stream =
                    new IsolatedStorageFileStream(filePath, FileMode.Open, this.storage))
                {
                    data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                }
            }
            catch (Exception)
            {

            }
            return data;
        }
 public void Load()
 {
     XmlSerializer serializer = new XmlSerializer(typeof(Configrations));
     using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream("a.txt", FileMode.Open, isf))
         {
             byte[] buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             using (MemoryStream ms = new MemoryStream(buffer))
             {
                 Configrations config = serializer.Deserialize(ms) as Configrations;
                 if (null != config)
                 {
                     Clone(this, config);
                 }
             }
         }
     }
 }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.TryGetValue("imageUri", out imageFileName))
            {
                FilenameText.Text = imageFileName;

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(imageFileName, System.IO.FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    // Allocate an array large enough for the entire file
                    byte[] data = new byte[stream.Length];
                    // Read the entire file and then close it
                    stream.Read(data, 0, data.Length);
                    stream.Close();

                    ExtendedImage image = new ExtendedImage();
                    image.LoadingCompleted +=
                        (o, ea) => Dispatcher.BeginInvoke(() => { AnimatedImage.Source = image; });

                    image.SetSource(new MemoryStream(data));
                }
            }
        }
        public byte[] Retrieve(string key)
        {
            var mutex = new Mutex(false, key);

            try
            {
                mutex.WaitOne();
                if (!File.FileExists(key))
                {
                    throw new Exception(string.Format("No entry found for key {0}.", key));
                }

                using (var stream = new IsolatedStorageFileStream(key, FileMode.Open, FileAccess.Read, File))
                {
                    var data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                    return ProtectedData.Unprotect(data, this.optionalEntropy);
                }
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
Exemple #13
0
		public void RegressionBNC354539 ()
		{
			string filename = "test-bnc-354539";
			byte[] expected = new byte[] { 0x01, 0x42, 0x00 };
			byte[] actual = new byte [expected.Length];

			using (IsolatedStorageFile file = IsolatedStorageFile.GetStore (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) {
				using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None, file)) {
					stream.Write (expected, 0, expected.Length);
				}
			}

			using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly ()) {
				using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read, file)) {
					stream.Read (actual, 0, actual.Length);
				}

				file.DeleteFile (filename);
			}
			
			Assert.AreEqual (expected, actual);
		}
        /// <summary>
        /// Read file from Isolated Storage and sends it to server
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void uploadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest webRequest = reqState.request;
            string callbackId = reqState.options.CallbackId;

            try
            {
                using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
                {
                    string lineStart = "--";
                    string lineEnd = Environment.NewLine;
                    byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;

                    if (!string.IsNullOrEmpty(reqState.options.Params))
                    {
                        Dictionary<string, string> paramMap = parseHeaders(reqState.options.Params);
                        foreach (string key in paramMap.Keys)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                            string formItem = string.Format(formdataTemplate, key, paramMap[key]);
                            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
                            requestStream.Write(formItemBytes, 0, formItemBytes.Length);
                        }
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    }
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(reqState.options.FilePath))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
                            return;
                        }

                        byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
                        long totalBytesToSend = 0;

                        using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
                        {
                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
                            string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
                            byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);

                            byte[] buffer = new byte[4096];
                            int bytesRead = 0;
                            //sent bytes needs to be reseted before new upload
                            bytesSent = 0;
                            totalBytesToSend = fileStream.Length;

                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                            requestStream.Write(headerBytes, 0, headerBytes.Length);

                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                if (!reqState.isCancelled)
                                {
                                    requestStream.Write(buffer, 0, bytesRead);
                                    bytesSent += bytesRead;
                                    DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId);
                                    System.Threading.Thread.Sleep(1);
                                }
                                else
                                {
                                    throw new Exception("UploadCancelledException");
                                }
                            }
                        }

                        requestStream.Write(endRequest, 0, endRequest.Length);
                    }
                }
                // webRequest

                webRequest.BeginGetResponse(ReadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                if (!reqState.isCancelled)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Restore the user settings from isolated storage.
        /// </summary>
        /// <param name="Type">The type of the settings object.</param>
        /// <param name="Section">The section in which the settings are stored.</param>
        /// <returns>A populated settings object.</returns>
        private static UserSettingsBase RestoreFromIsolatedStorage(Type Type, string Section)
        {
            XmlSerializer formatter = new XmlSerializer(Type);
            IsolatedStorageFileStream settingsFile;

            try
            {
                settingsFile = new IsolatedStorageFileStream(Section + ".Config", FileMode.Open, IsolatedStorageFile.GetUserStoreForDomain());

            }
            catch (Exception ex)
            {
                throw (new UserSettingsException("User settings not found in isolated storage", ex));

            }

            try
            {
                byte[] buffer = new byte[Convert.ToInt32(settingsFile.Length) - 1 + 1];

                settingsFile.Read(buffer, 0, Convert.ToInt32(settingsFile.Length));

                MemoryStream stream = new MemoryStream(buffer);

                return ((UserSettingsBase) formatter.Deserialize(stream));

            }
            catch (Exception ex)
            {
                throw (new UserSettingsException("User settings could not be loaded from isolated storage", ex));
            }
            finally
            {
                settingsFile.Close();
            }
        }
		public void LoadAllSubscriptions()
		{
			// List all the folders for now
			//
			IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

			string[] directoryNames = myStore.GetDirectoryNames();

			Subscriptions.Clear();

			foreach (string name in directoryNames)
			{
				if (name == "Shared") continue;

				// Read all details.xml files.
				//
				using (var isoFileStream = new IsolatedStorageFileStream(name + "\\details.xml", FileMode.Open, myStore))
				{
					byte[] file = new byte[isoFileStream.Length];
					isoFileStream.Read(file, 0, (int)isoFileStream.Length);

					Subscription info = ViewModels.SubscriptionManager.GetSubscriptionFromFile(file);
					Subscriptions.Add(info);
				}
			}

			if (Subscriptions.Count == 0)
			{

			}
		}
Exemple #17
0
        private object ReadField(IsolatedStorageFileStream fileStream)
        {
            if (fileStream.Length == 0)
            {
                return null;
            }

            byte[] fieldBytes = new byte[fileStream.Length];
            fileStream.Read(fieldBytes, 0, fieldBytes.Length);
            object fieldValue = SerializationUtility.ToObject(fieldBytes);
            return fieldValue;
        }
        public byte[] GetAvatarImage(string strHash)
        {
            byte [] bImage = null;
            IsolatedStorageFile storage = null;

            storage = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);

            string strFileName = string.Format("{0}/{1}", AccountFolder, strHash);
            if (storage.FileExists(strFileName) == false)
            {
                storage.Dispose();
                return null;
            }

            IsolatedStorageFileStream stream = null;
            try
            {
                stream = new IsolatedStorageFileStream(strFileName, System.IO.FileMode.Open, storage);

                bImage = new byte[stream.Length];
                stream.Read(bImage, 0, bImage.Length);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (stream != null)
                    stream.Close();

                storage.Dispose();
            }

            return bImage;
        }
Exemple #19
0
 public static string ReadAllText(this IsolatedStorageFileStream stream)
 {
     byte[] buffer = new byte[stream.Length];
     stream.Read(buffer, 0, buffer.Length);
     return(Encoding.UTF8.GetString(buffer));
 }
 public static string ReadFromFile(string Filename)
 {
     string string_data = string.Empty;
     try
     {
         using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
         {
             lock (iso)
             {
                 if (!FileExists(Filename))
                     return string.Empty;
                 IsolatedStorageFileStream isf = new IsolatedStorageFileStream(Filename, System.IO.FileMode.Open, iso);
                 byte[] data = new byte[(int)isf.Length];
                 isf.Read(data, 0, (int)isf.Length);
                 isf.Close();
                 string_data = Encoding.UTF8.GetString(data, 0, data.Length);
             }
         }
     }
     catch (Exception e)
     {
         ErrorLogging.Log("ISOHelper", e.Message, "ISOHelperError", Filename);
     }
     return string_data;
 }
		public void WriteThenRead ()
		{
			IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication ();
			using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream ("moon", FileMode.Create, isf)) {
				byte [] data = new byte [2] { 0x00, 0x01 };
				fs.Write (data, 0, 1);
				fs.WriteByte (0xff);
			}
			using (IsolatedStorageFileStream fs = isf.OpenFile ("moon", FileMode.Open)) {
				byte [] data = new byte [1];
				Assert.AreEqual (1, fs.Read (data, 0, 1), "1");
				Assert.AreEqual (0x00, data[0], "0x00");
				Assert.AreEqual (0xff, fs.ReadByte (), "0xff");

				isf.Remove (); // this removed everything
				Assert.Throws (delegate { fs.Read (data, 1, 1); }, typeof (IsolatedStorageException), "Remove/Write"); // Fails in Silverlight 3
				Assert.Throws (delegate { fs.ReadByte (); }, typeof (IsolatedStorageException), "Remove/WriteByte");
				isf.Dispose ();
				Assert.Throws (delegate { fs.Read (data, 1, 1); }, typeof (ObjectDisposedException), "Dispose/Write");
				Assert.Throws (delegate { fs.ReadByte (); }, typeof (ObjectDisposedException), "Dispose/WriteByte");
			}
			isf = IsolatedStorageFile.GetUserStoreForApplication ();
			Assert.AreEqual (0, isf.GetFileNames ().Length, "Empty");
		}
Exemple #22
0
        private async void encode(object sender, RoutedEventArgs e)
        {
           // player.Stop();
            LameWrapper lame = new LameWrapper();
            lame.InitialLame(44100, 44100, 2, 5);
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream WorkStream = isf.CreateFile("encoded_mp3.mp3"))
            {
                using (PCMStream = isf.OpenFile("/decoded_pcm.pcm", FileMode.Open))
                {
                    int totalread=0;
                    while (PCMStream.Position<PCMStream.Length)
                    {
                        byte[] rawbytes=new byte[65536];

                        int actualcount=PCMStream.Read(rawbytes, 0, 65536);
                      //  MessageBox.Show("read:" + actualcount);
                        totalread += actualcount;
                        PCMStream.Position = totalread;
                        IBuffer PCMSampleBuffer = WindowsRuntimeBufferExtensions.AsBuffer(rawbytes, 0, rawbytes.Length);
                     
                        CompressedMp3Content citem = await lame.EncodePcm2Mp3(PCMSampleBuffer);
                      //  MessageBox.Show(citem.Mp3Data.Length+"");
                        WorkStream.Write(citem.Mp3Data, 0, citem.Mp3Data.Length);
                        WorkStream.Flush();
                        statustb.Text = "position: " + PCMStream.Position + " total: " + PCMStream.Length ;
                    }
                }
            }

            isf.Dispose();
            lame.CloseLame();
        }
        /// <summary>
        /// Responsible for reading value from IsolatedStorage using given IsolatedStorageFileStream reference. Subclasses
        /// may override this method to provide different implementations of reading from IsolatedStorage.
        /// </summary>
        /// <param name="fileStream">Stream from which value should be written. May not be null.</param>
        /// <param name="encrypted">True if item is stored encrypted</param>
        /// <returns>Value read from Isolated Storage. May be null if value stored is null</returns>
        protected virtual object ReadField(IsolatedStorageFileStream fileStream, bool encrypted)
        {
            if (fileStream.Length == 0)
            {
                return null;
            }

            byte[] fieldBytes = new byte[fileStream.Length];
            fileStream.Read(fieldBytes, 0, fieldBytes.Length);
            if (encrypted)
            {
                fieldBytes = DecryptValue(fieldBytes);
            }
            object fieldValue = SerializationUtility.ToObject(fieldBytes);
            return fieldValue;
        }
 /// <summary>
 /// 读取本地文件信息,SilverLight缓存中
 /// </summary>
 /// <param name="rFileName">存储文件名</param>
 /// <returns>返回文件数据</returns>
 public static byte[] ReadSlByteFile(string rFileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
     System.IO.Stream stream = null;
     byte[] buffer = null;
     try
     {
         isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
         if (!isf.FileExists(rFileName)) return null;
         stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, isf);
         buffer = new byte[stream.Length];
         stream.Read(buffer, 0, (int)stream.Length);
     }
     finally
     {
         if (stream != null)
         {
             stream.Close(); // Close the stream
             stream.Dispose();
         }
         isf.Dispose();
     }
     return buffer;
 }
Exemple #25
0
        private XDocument ReadXmlFile(string fileName)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                //init folder
                if (!store.DirectoryExists(@"cache"))
                {
                    store.CreateDirectory(@"cache");
                }

                if (!store.DirectoryExists(@"cache/xml"))
                {
                    store.CreateDirectory(@"cache/xml");
                }

                //read existing file
                if (store.FileExists(@"cache/xml/" + fileName + ".xml"))
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"cache/xml/" + fileName + ".xml", System.IO.FileMode.Open, store))
                    {
                        //return XDocument.Load(stream);

                        //read file to byte array
                        byte[] bytesInStream = new byte[stream.Length];
                        stream.Read(bytesInStream, 0, bytesInStream.Length);

                        //decrypt
                        byte[] decryptedBytes = ProtectedData.Unprotect(bytesInStream, XmlOptionalEntropy);

                        //convert byte array to string
                        string xml_text = Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length);

                        return XDocument.Parse(xml_text, LoadOptions.None);
                    }
                }

                return null;
            }
        }
 private static string GetMainPageString(string elementName)
 {
     using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) {
         using (var file = new IsolatedStorageFileStream("mainpage.xml", FileMode.Open, iso)) {
             var bb = new byte[file.Length];
             file.Read(bb, 0, bb.Length);
             using (var oStream = new MemoryStream(bb)) {
                 XDocument xDoc = XDocument.Load(oStream);
                 try {
                     return xDoc.Element("items").Element(elementName).Value;
                 }
                 catch (NullReferenceException) {
                     return string.Empty;
                 }
             }
         }
     }
 }
 private static void SetMainPageString(string value, string elementName)
 {
     using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) {
         XDocument xDoc;
         using (var file = new IsolatedStorageFileStream("mainpage.xml", FileMode.Open, iso)) {
             var bb = new byte[file.Length];
             file.Read(bb, 0, bb.Length);
             using (var oStream = new MemoryStream(bb)) {
                 xDoc = XDocument.Load(oStream);
                 if (!xDoc.Element("items").Elements(elementName).Any())
                     xDoc.Element("items").Add(new XElement(elementName, value));
                 xDoc.Element("items").Element(elementName).Value = value;
             }
         }
         using (var file = new IsolatedStorageFileStream("mainpage.xml", FileMode.Create, iso)) {
             byte[] bb = Encoding.UTF8.GetBytes(xDoc.ToString());
             file.Write(bb, 0, bb.Length);
         }
     }
 }
Exemple #28
0
        private static byte[] ReadFile(string file)
        {
            string filename = AvatarsDirectory + Path.DirectorySeparatorChar + file;

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                if (storage.GetDirectoryNames(AvatarsDirectory).Length == 0)
                {
                    storage.CreateDirectory(AvatarsDirectory);
                }

                using (var stream =
                    new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage))
                {
                    var buffer = new byte[stream.Length];

                    stream.Read(buffer, 0, buffer.Length);

                    return buffer;
                }
            }
        }
        /// <summary>
        /// Read file from Isolated Storage and sends it to server
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void WriteCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
                {
                    string lineStart = "--";
	                string lineEnd = Environment.NewLine;
                    byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;

                    if (uploadOptions.Params != null)
                    {
                        Dictionary<string, object> customParams = uploadOptions.Params;
                        foreach (string key in customParams.Keys)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                            string formItem = string.Format(formdataTemplate, key, customParams[key]);
                            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
                            requestStream.Write(formItemBytes, 0, formItemBytes.Length);
                        }
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    }
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(uploadOptions.FilePath))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)));
                            return;
                        }

                        using (FileStream fileStream = new IsolatedStorageFileStream(uploadOptions.FilePath, FileMode.Open, isoFile))
                        {
                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
                            string header = string.Format(headerTemplate, uploadOptions.FileKey, uploadOptions.FileName, uploadOptions.MimeType);
                            byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
                            requestStream.Write(headerBytes, 0, headerBytes.Length);
                            byte[] buffer = new byte[4096];
                            int bytesRead = 0;
                            
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                requestStream.Write(buffer, 0, bytesRead);
                                bytesSent += bytesRead;
                            }
                        }
                        byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
                        requestStream.Write(endRequest, 0, endRequest.Length);
                    }
                }
                webRequest.BeginGetResponse(ReadCallback, webRequest);
            }
            catch(Exception e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)));
                });
            }
        }
        private void button3_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // Obtain a virtual store for the application.
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                // Specify the file path and options.
                GlobalVar.client.Send("" + 2 + "\n");
                GlobalVar.client.Send(RemoteUpload.Text + "\n");
                using (var isoFileStream = new IsolatedStorageFileStream("MyFolder\\" + RemoteUpload.Text, FileMode.Open, myStore))
                {
                    // Read the data.
                    using (var isoFileReader = new StreamReader(isoFileStream))
                    {
                        int readbytes = 12288;
                        while (readbytes == 12288)
                        {
                            byte[] buffer = new byte[12288];
                            readbytes = isoFileStream.Read(buffer, 0, 12288);

                            String tobesend = "";
                            int i = 0;
                            //int temp_send = isoFileStream.ReadByte();
                            while (i != readbytes)
                            {
                                //GlobalVar.client.Send(temp_send + "\n");
                                //temp_send = isoFileStream.ReadByte();
                                tobesend = tobesend + ((int)buffer[i]).ToString() + "\n";
                                i++;
                            }
                            GlobalVar.client.Send(tobesend);
                        }

                        GlobalVar.client.Send("null" + "\n");
                    }
                }
                // GlobalVar.client.Send("-1"+ "\n");

            }
            catch
            {
                // Handle the case when the user attempts to click the Read button first.
                //txtRead.Text = "Need to create directory and the file first.";
            }
        }
Exemple #31
0
		private static Guid GetOrCreateOriginIdentity() {
			Requires.ValidState(file != null);
			Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);

			Guid identityGuid = Guid.Empty;
			const int GuidLength = 16;
			using (var identityFileStream = new IsolatedStorageFileStream("identity.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, file)) {
				if (identityFileStream.Length == GuidLength) {
					byte[] guidBytes = new byte[GuidLength];
					if (identityFileStream.Read(guidBytes, 0, GuidLength) == GuidLength) {
						identityGuid = new Guid(guidBytes);
					}
				}

				if (identityGuid == Guid.Empty) {
					identityGuid = Guid.NewGuid();
					byte[] guidBytes = identityGuid.ToByteArray();
					identityFileStream.SetLength(0);
					identityFileStream.Write(guidBytes, 0, guidBytes.Length);
				}

				return identityGuid;
			}
		}
Exemple #32
0
        /*  private void LayoutRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            Sender.DetachDuplexOutputChannel();
        }*/
        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            textBox4.Text = "test";
            textBox2.Text = "";
            IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();

            IsolatedStorageFileStream stream = new IsolatedStorageFileStream("Intro English.jpg", FileMode.Open, fileStorage);
            //textBox4.Text = "1 step passed!";
            var image = new BitmapImage();
               // textBox4.Text = "2 step passed!";
            image.SetSource(stream);
            //textBox4.Text = "3 step passed!";
            image1.Source = image;
            //textBox4.Text = "4 step passed!";
            //stream.Seek(0,0);

            /*for (int i = 0; i < stream.Length; i++)
            {
                file[i] = stream.Read(
            }*/
            //string sim = "";
            byte[] img = new byte[stream.Length];
            long seekPos = stream.Seek(0, SeekOrigin.Begin);
            stream.Read(img, 0, img.Length);
            seekPos = stream.Seek(0, SeekOrigin.Begin);
               /* var cnt = 0;
            foreach (byte x in img)
            {
                textBox4.Text = cnt.ToString() + ":" + x.ToString();
                cnt++;
            }*/
            textBox4.Text = img[3000].ToString();

              /*  IPAddress ipa = IPAddress.Parse("127.0.0.1");
            IPEndPoint end = new IPEndPoint(ipa, 8001);*/
            TcpClient to_transmit = new TcpClient("127.0.0.1",8001);

               // to_transmit.Connect(textBox1.Text, 8001);
            //to_transmit.Connect(end);

            NetworkStream trans_stream = to_transmit.GetStream();
            trans_stream.Write(img, 0, img.Length);

            if (to_transmit.Connected != true) textBox4.Text = "Conn error!";

            byte[] resp = new byte[1000000];
            int max = trans_stream.Read(resp, 0, 1000000);

            for (int i = 0; i < max; i++) textBox2.Text += Convert.ToChar(resp[i]);

            trans_stream.Dispose();
            to_transmit.Dispose();

            //to_transmit.EndConnect();
            //textBox4.Text = stream.Length.ToString();
        }