I am using a StreamReader in WeatherController.cs to read data form a CSV file. And in my MainWindow i am using a FileChooseDialog to find the file to read from. Like so:
protected void OnButton2Clicked (object sender, EventArgs e)
{
//Open file dialog and choose a file.
Gtk.FileChooserDialog fc=
new Gtk.FileChooserDialog("Choose the file to open",
this,
Gtk.FileChooserAction.Open,
"Cancel",Gtk.ResponseType.Cancel,
"Open",Gtk.ResponseType.Accept);
fc.Filter = new FileFilter ();
fc.Filter.AddPattern ("*.csv");
if (fc.Run() == (int)Gtk.ResponseType.Accept)
{
b_Next.Sensitive = true;
System.IO.FileStream file = System.IO.File.OpenRead(fc.Filename);
file.Close();
}
//Destroy() to close the File Dialog
fc.Destroy();
}
How do i get the file path from this file to be used in my WeatherController.cs StreamReader?
My StreamReader:
using (StreamReader sr = new StreamReader (file))
string folder = Path.GetDirectoryName( file );
Related
It says System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/csharpfile.txt". for the file path directory
//FILESTREAM
private static void FileStream()
{
Console.Clear();
FileStream fs = new FileStream("/storage/emulated/0/FPAct8_(Ray)/csharpfile.txt",
FileMode.Create);
fs.Close();
Console.WriteLine("File has been created and the path is /storage/emulated/0/FPAct8_(Ray)/csharpfile.txt");
}
//STREAMWRITER
private static void StreamWriter()
{
string file = #"/storage/emulated/0/FPAct8_(Ray)/csharpfile.txt";
using(StreamWriter writer = new StreamWriter (file)){
writer.Write("Hello!");
writer.Write("This is Ray");
writer.Write("BSIT-1C");
writer.Write("This is StreamWriter");
}
Console.WriteLine("Data Saved Successfully");
}
//STREAMREADER
private static void StreamReader()
{
string file = #"/storage/emulated/0/FPAct8_(Ray)/csharpfile2.txt";
using(StreamReader reader = new StreamReader (file)){
Console.WriteLine(reader.ReadToEnd());
}
}
//TEXTWRITER
private static void TextWriter()
{
string file = #"/storage/emulated/0/FPAct8_(Ray)/csharpfile.txt";
using (TextWriter writer = File.CreateText(file)){
writer.WriteLine("Hello");
writer.WriteLine("This is TextWriter");
}
Console.WriteLine("Entry stored successfully");
}
//TEXTREADER
private static void TextReader()
{
string filepath = #"/storage/emulated/0/FPAct8_(Ray)/csharpfile.txt";
using(TextReader tr = File.OpenText(filepath)){
Console.WriteLine(tr.ReadToEnd());
}
I've already search on google and here about the file path directory and the only thing I found is /storage/emulated/0/ but it doesn't work and the others are for desktop but what I need is for android.
Dcoder is the IDE that I use, btw.
Edit: I also try Phone Storage:\\csharpfile.txt but this time it says System.UnauthorizedAccessException: Access to the path "/home/user/Phone Storage:\csharpfile.txt" is denied. and I need it to be directed to a folder because that's what my teacher says but when I add a folder it goes back to could not find path.
Thank you very much!
use
Server.MapPath(#"/storage/emulated/0/FPAct8_(Ray)/csharpfile.txt");
I don't want the user to decide which location of the wav file should be saved , and automatically save it in D:\
private void btnAdd_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"D:\CIS";
saveFileDialog.FileName = textBox1.Text;
Stream fileStream = saveFileDialog.OpenFile();
this.encoder.Save(fileStream);
}
If you meant you don't want to prompt the user on where to save the file, and rather just save the file directly, just do
using (Stream fileStream = File.Open(Path.Combine(#"D:\CIS",textBox1.Text) , FileMode.Open))
{
this.encoder.Save(fileStream), FileMode.Open);
}
Simply open a new file with the filename that you want and write the data to it like this:
string filename = "d:\\file1.wav";
using (Stream fileStream = File.OpenWrite(filename))
{
this.encoder.Save(fileStream);
}
How to create XML file to some folder?
isoStream = new IsolatedStorageFileStream("**Folder/XmlFile.xml**", FileMode.Create, isoStore);
Snatched directly from the Quickstart: Working with files and folders in Windows Phone 8
Check out the section "Creating a folder and writing to a text file"
private async void btnWrite_Click(object sender, RoutedEventArgs e)
{
await WriteToFile();
// Update UI.
this.btnWrite.IsEnabled = false;
this.btnRead.IsEnabled = true;
}
private async Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.textBox1.Text.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("DataFile.txt",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
Below function will save the Jagged array double[][] to the XML. You may use it by modify to your own data type:
private void Save(double[][] m, string filePath)
{
//Open a file stream
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
// Create a xml Serializer object
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(double[][]));
xmlSer.Serialize(fs, m);
// Close the file stream
fs.Close();
}
Just instead of the double [][] m you should put your own type.
I am trying to separate the MIME gui from the code i need. I am almost there just one more gui element i dont know how to replace. This element is the openfiledialog. Here a code snippet.
Program.cs
var sfd = new OpenFileDialog();
sfd.FileName = "C:\\eml\\" + validOutputFilename;
try
{
var writer = new MimeMessageWriter();
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
}
catch (Exception ex)
{
//ignore
// need to log
}
message is an IMessage. A class created to store the information about an eml file. The open file dialog is allowing you to put in the file name with an eml extension and that is all. write.Write expects an IMessage and a stream. Inside writer.Write the file is being written The only part of the file that uses this code is when the file itself is writen at the end and write out any attachments. Here are those code snippets.
*MimeMessageWriter
-the attachment uses it here
var embeddedMessage = attachment.OpenAsMessage();
var messageWriter = new MimeMessageWriter();
var msgStream = new MemoryStream();
messageWriter.Write(embeddedMessage, msgStream);
var messageAttachment = ew DotNetOpenMail.FileAttachment(msgStream.ToArray());
messageAttachment.ContentType = "message/rfc822";
messageAttachment.FileName = filename + ".eml";
outMessage.AddMixedAttachment(messageAttachment);
-write out the file part of the file
using (var sw = new StreamWriter(stream))
sw.Write(outMessage.ToDataString());
I want to replace openFileDialog with something that will allow me to pass the filename to write out file in the MimeMessageWriter
Replace
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
with
string fileName = #"c:\eml\myAttachment.eml";
using ( FileStream fs = new FileStream( fileName, FileMode.CreateNew ) )
{
writer.Write( message, fs )
}
See also: http://msdn.microsoft.com/de-de/library/47ek66wy.aspx
I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.