2014-12-09 3 views
0

Я пытаюсь сделать программу, в которой хранятся много файлов (5-15) .txt в изолированной памяти телефона. Я заметил, как легко читать эти файлы с такими программами, как Windows Phone Power Tools, поэтому я решил их зашифровать. Я использую эту ссылку в качестве учебника:Windows Phone 7: Расшифровка большого количества файлов из изолированного хранилища

http://msdn.microsoft.com/en-us/library/windows/apps/hh487164(v=vs.105).aspx

Шифрование работает отлично, как и я, очевидно, сохранение одного файла одновременно. Однако у меня возникают проблемы, пытаясь их расшифровать. Как мне изменить свой код, чтобы я мог расшифровать многие .txt-файлы? Ниже приведены мои коды, которые я использую в данный момент:

 private void IsoRead() 
    { 
     System.IO.IsolatedStorage.IsolatedStorageFile local = 
     System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); 

     string[] filenames = local.GetFileNames("./DataFolder/*.txt*"); 
     foreach (var fname in filenames) 
     { 
      //retrieve byte 
       byte[] ProtectedByte = this.DecryptByte(); 
      //decrypt with Unprotect method 
       byte[] FromByte = ProtectedData.Unprotect(ProtectedByte, null); 
      //convert from byte to string 
       fText = Encoding.UTF8.GetString(FromByte, 0, FromByte.Length); 

       this.Items.Add(new itemView() { LineOne = fname, LineTwo = fText }); 
     }   
    } 

И еще один:

 private byte[] DecryptByte() 
    { 
     // Access the file in the application's isolated storage. 
     IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); 

     IsolatedStorageFileStream readstream = new IsolatedStorageFileStream 
      ("DataFolder\\"/*Here's where I'm having problems with*/, System.IO.FileMode.Open, FileAccess.Read, file); 

     // Read the written data from the file. 
     Stream reader = new StreamReader(readstream).BaseStream; 
     byte[] dataArray = new byte[reader.Length]; 
     reader.Read(dataArray, 0, dataArray.Length); 
     return dataArray; 

    } 

Так в основном программа имеет страницу ListView, которые получают это файлы из изолированного хранилища. Если кто-то тронут, он переходит на новую страницу, в которой отображается то, что написано в ней.

Вопрос с бонусом: могу ли я зашифровать папки в WP7/WP8?

Редактировать: добавлена ​​одна строка кода в IsoRead.

+0

Какие проблемы вы с точно? Производительность связана? – FunksMaName

+0

@FunksMaName Мой вопрос: Как мне изменить свой код, чтобы я мог расшифровать многие .txt-файлы? Я отредактировал мое сообщение, так что теперь вопрос теперь легче заметить и для других. – user3616427

+0

Хорошо, я сейчас задаю вопрос. Я адаптировал пример здесь как ответ, чтобы он работал для нескольких файлов. http://msdn.microsoft.com/en-us/library/windows/apps/hh487164%28v=vs.105%29.aspx Я думаю, что у вас проблемы с этой строкой, потому что вы не пытаетесь прочитать действительный файл , «DataFolder \\» не указывает на файл, это папка, поэтому вам может потребоваться указать правильное имя файла. – FunksMaName

ответ

0

Xaml:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
     <StackPanel> 
      <Button Content="Write Random File" Click="WriteFile" VerticalAlignment="Top" /> 
      <Button Content="Read files File" Click="ReadFiles" VerticalAlignment="Top" /> 
     </StackPanel> 
    </Grid> 

Код:

public partial class MainPage : PhoneApplicationPage 
{ 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
    } 

    private const string FilePath = "{0}.txt"; 

    private readonly List<ItemView> items = new List<ItemView>(); 

    private void WriteFile(object sender, RoutedEventArgs e) 
    { 
     var fileName = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture); 

     // Convert text to bytes. 
     byte[] data = Encoding.UTF8.GetBytes(fileName); 

     // Encrypt byutes. 
     byte[] protectedBytes = ProtectedData.Protect(data, null); 

     // Store the encrypted bytes in iso storage. 
     this.WriteToFile(protectedBytes, fileName); 
    } 

    private void ReadFiles(object sender, RoutedEventArgs e) 
    { 
     items.Clear(); 

     using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      var files = isoStore.GetFileNames("*.txt"); 

      foreach (var file in files) 
      { 
       // Retrieve the protected bytes from isolated storage. 
       byte[] protectedBytes = this.ReadBytesFromFile(file); 

       // Decrypt the protected bytes by using the Unprotect method. 
       byte[] bytes = ProtectedData.Unprotect(protectedBytes, null); 

       // Convert the data from byte to string and display it in the text box. 
       items.Add(new ItemView { LineOne = file, LineTwo = Encoding.UTF8.GetString(bytes, 0, bytes.Length) }); 
      } 
     } 

     //Show all the data... 
     MessageBox.Show(string.Join(",", items.Select(i => i.LineTwo))); 
    } 

    private void WriteToFile(byte[] bytes, string fileName) 
    { 
     // Create a file in the application's isolated storage. 
     using (var file = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      using (var writestream = new IsolatedStorageFileStream(string.Format(FilePath, fileName), System.IO.FileMode.Create, System.IO.FileAccess.Write, file)) 
      { 
       // Write data to the file. 
       using (var writer = new StreamWriter(writestream).BaseStream) 
       { 
        writer.Write(bytes, 0, bytes.Length); 
       } 
      } 
     } 
    } 

    private byte[] ReadBytesFromFile(string filePath) 
    { 
     // Access the file in the application's isolated storage. 
     using (var file = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      using (var readstream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Open, FileAccess.Read, file)) 
      { 
       // Read the data in the file. 
       using (var reader = new StreamReader(readstream).BaseStream) 
       { 
        var ProtectedPinByte = new byte[reader.Length]; 

        reader.Read(ProtectedPinByte, 0, ProtectedPinByte.Length); 

        return ProtectedPinByte; 
       } 
      } 
     } 
    } 
} 

public class ItemView 
{ 
    public string LineOne { get; set; } 
    public string LineTwo { get; set; } 
} 
+0

Спасибо FunksMaName, это действительно помогло. К сожалению, это не может поддержать этот ответ из-за низкой репутации, но я отмечаю это как принятое. – user3616427

Смежные вопросы