2012-10-13 67 views
1

我是一名C++開發人員,最近轉向了WPF C#的世界。我正在開發一個應用程序,我必須通過使用fileopendialog加載文本文件,選擇文件並將其保存在組合框中,然後單擊writebutton,我應該使用文本文件中存在的數據執行一些操作。在按鈕上執行文件操作單擊WPF

我用C做了++如下:

if(button == m_writeButton) 
{ 
    // get the data from the file 
    File m_binFile = m_fileChoice->getCurrentFile(); 
    MemoryBlock m_data; 

    m_binFile.loadFileAsData(m_data); 
    size_t blockSize = m_data.getSize(); 

    unsigned char *f_buffer; 
    f_buffer = (unsigned char *)m_data.getData(); 
    unsigned cnt = 0; 

    // Some code 
} 

我做到了,在C#如下:

<ComboBox Name="WriteFileCombo" > 
         <ComboBoxItem Content="Firmware To Download" /> 
         <ComboBoxItem Content="{Binding FirmwarePath}" /> 
</ComboBox> 
<Button Content="..." Command="{Binding Path=WriteFilePathCommand}" Name="FileDialogBtn"/>      

<Button Content="Write File" Command="{Binding Path=WriteFileCommand}" Name="WriteFileBtn" /> 

視圖模型類:

private string _selectedFirmware; 
    public string FirmwarePath 
    { 
     get { return _selectedFirmware; } 
     set 
     { 
      _selectedFirmware = value; 
      OnPropertyChanged("FirmwarePath"); 
     } 
    } 

// Gets called when Browse Button (...) is clicked 
private void ExecuteWriteFileDialog() 
    { 
     var dialog = new OpenFileDialog { InitialDirectory = _defaultPath }; 
     dialog.DefaultExt = ".txt"; 
     dialog.Filter = "TXT Files (*.txt)|*.txt"; 
     dialog.ShowDialog(); 
     FirmwarePath = dialog.FileName; 

     WriteFileCommandExecuted(); 
    } 

// Gets called when Write Button is clicked 
public void WriteFileCommandExecuted() 
    { 
     // same logic as in c++ 
    } 

怎麼辦我使用我的中的C++代碼執行相同的操作方法?

請幫助:)

回答

1
//Inside void WriteFileCommandExecuted() 

System.IO.StreamReader sr = new System.IO.StreamReader("File Path"); 
       textBox1.Text = sr.ReadToEnd(); 

     //Or if you need more control 

     System.IO.FileStream fs = new System.IO.FileStream(FirmwarePath, System.IO.FileMode.CreateNew); 
     System.IO.StreamReader sr = new System.IO.StreamReader(fs); 
     string textdata = sr.ReadToEnd(); 
     int fileSize = (int)new System.IO.FileInfo(FirmwarePath).Length; 

     Byte f_buffer = new Byte(); 
     f_buffer = Convert.ToByte(textdata); 
     int cnt = 0; 

    //The FirmwarePath is the path returned to you by your file dialog box. 
    //If you want to write the class you will need to instantiate is System.IO.StreamWriter then //invoke the "write" method 
+0

嗯,這讀取文本文件,並將其存儲。我想要做更多。檢查代碼:)'MemoryBlock'基本上創建一個大小爲0的未初始化塊。 dat如何在C#中完成? – StonedJesus

+1

它不能,C#代碼運行在託管環境(.Net運行時) – Yohannes

+0

檢查答案我更新:)看看它是如何在C++中完成的,它是正確的嗎? – StonedJesus

相關問題