When I try to open a .txt file it only shows its location in my textbox.
I am out of ideas:( hope you can help me...
code:
private void OpenItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
System.IO.StringReader OpenFile = new System.IO.StringReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
}
A StringReader reads the characters from the string you pass to it -- in this case, the file's name. If you want to read the contents of the file, use a StreamReader:
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
Use File.ReadAllText
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
I'd use the File.OpenText() method for reading text-files. You should also use using statements to properly dispose the object.
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Make sure a file was selected
if ((myStream = openFileDialog1.OpenFile()) != null) {
// Open stream
using (StreamReader sr = File.OpenText(openFileDialog1.FileName))
{
// Read the text
richTextBox1.Text = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured: " + ex.Message);
}
}
That's easy. This is what you need to do:
1) Put using System.IO; above namespace.
2) Create a new method:
public static void read()
{
StreamReader readme = null;
try
{
readme = File.OpenText(#"C:\path\to\your\.txt\file.txt");
Console.WriteLine(readme.ReadToEnd());
}
// will return an invalid file name error
catch (FileNotFoundException errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
// will return an invalid path error
catch (Exception errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
finally
{
if (readme != null)
{
readme.Close();
}
}
}
3) Call it in your main method: read();
4) You're done!
Related
This script generate a txt file in Download folder on Android device.
public class WriteCSVInDownloadFolder : MonoBehaviour
{
public TMP_Text Text;
private void Start()
{
try
{
var txtpath = GetDownloadFolder() + "/Test.txt";
FileStream file = new FileStream(txtpath, FileMode.Create, FileAccess.Write);
}
catch (IOException e)
{
Text.text = e.Message;
}
}
public static string GetDownloadFolder()
{
string[] temp = (Application.persistentDataPath.Replace("Android", "")).Split(new string[] { "//" }, System.StringSplitOptions.None);
return (temp[0] + "/Download");
}
}
But, when I manually remove this file and execute this script again, I receive an exception: "File already exists"
Therefore , I have tried to use FileMode.Truncate and File.Exists functions, however, I receive another exception: "Could not find file"
Any idea?
Update 1
I tried to solve the problem with Dispose() method, but the problem persist.
TextWriter writer = File.CreateText(path);
writer.Write("Hello World");
writer.Flush();
writer.Dispose();
Update 2
I tried to remove residual entries getting Uri, but not working.
Uri uri = new Uri(txtpath);
if (uri.IsFile)
{
string filename = Path.GetFileName(uri.LocalPath);
Text.text = filename;
File.Delete(uri.LocalPath);
}
Update 3
Current code
private void Awake()
{
try
{
txtpath = FileManager.GetFolder("/Download") + "/Test.txt";
if (File.Exists(txtpath))
{
Text.text = "Exist";
File.Delete(txtpath);
}
else
{
Text.text = "Not existe";
FileStream file = new FileStream(txtpath, FileMode.Create, FileAccess.Write);
}
}
catch (IOException e)
{
Text.text = e.Message;
}
}
Update 4
New: I tried to use Path.Combine.
Exception thrown: "Access to the path "..." is denied".
public class ReadCSVInDownloadFolder : MonoBehaviour
{
public TMP_Text Text;
private string path;
private void Awake()
{
try
{
path = Path.Combine("storage","emulated","0","Download", "Test.csv");
Text.text = File.ReadAllText(path);
}
catch (Exception e)
{
Text.text = e.Message;
}
}
}
While creating your file it has been indexed by the media store.
So there is an entry for the file in the media store.
There are a bunch of sloppy programmed file managers that delete the file but leave the entry.
So first delete that entry and then you go again.
I'm trying to make a program that loads a configuration file from another application.
If the file exists, it loads it and displays a message, but if the configuration file is not valid, it displays an error message and then opens a dialog box to load the correct file. But if the user reloads the wrong file, the same dialog box should appear again but that's when my code fails.
Similarly, if the file did not exist from the beginning, it displays a dialog box to load the file, but if it is given to cancel the dialog box or an incorrect file is selected again, my code fails.
I know that the solution would be to use loops but I'm not sure how to structure it.
Pd: searchfile() is my function to open dialog box and readconfig() is my function to read config file of another application.
strfilenamepath = #"C:\Users\test\dogs.exe.config";
if (File.Exists(strfilenamepath))
{
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
else
{
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
readConfig(strfilenamepath);
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
It is easier to design it if you extract the reading logic to another method that handles exceptions and returns a Boolean to signal the success and the computed result. The TryDoSomething pattern does exactly this.
In pseudo code
public bool TryReadConfig(string path, out string[] valores)
{
valores = null;
try {
valores = read the values;
return true;
} catch {
Display message;
return false;
}
}
The main loop in pseudo code
strfilenamepath = #"C:\Users\test\dogs.exe.config";
while (true) {
if (File.Exists(strfilenamepath) && TryReadConfig(strfilenamepath, out var valores)) {
Do something with the valores;
break;
}
var ofd = new OpenFileDialog{ ... };
if (ofd.ShowDialog() == DialogResult.OK) {
strfilenamepath = ofd.Filename;
} else {
break; // The user canceled the operation.
}
}
You can do something like this:
try
{
//Code to try open the file to memory
}
catch (Exception ex)
{
while (true)
{
MessageBox.Show(#"Select an valid file");
var path = searchFile();
if (string.IsNullOrWhiteSpace(path))
continue;
try
{
//Code to try open the file to memory
}
catch (Exception ex2)
{
MessageBox.Show(#"The selected file is not valid");
continue;
}
break;
}
}
I run a Method, there're three part, part 1 and 3 are all the same to "read text file",
and part2 is to save string to text file,
// The Save Path is the text file's Path, used to read and save
// Encode can use Encoding.Default
public static async void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE)
{
// Part1
try
{
using (StreamReader sr = new StreamReader(SavePath, ENCODE))
{
string result = "";
while (sr.EndOfStream != true)
result = result + sr.ReadLine() + "\n";
MessageBox.Show(result);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Part2
try
{
using (FileStream fs = new FileStream(SavePath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs, ENCODE))
{
await sw.WriteAsync(StrToSave);
await sw.FlushAsync();
sw.Close();
}
MessageBox.Show("Save");
fs.Close();
}
}
// The Run End Here And didn't Continue to Part 3
catch (Exception e)
{
Console.WriteLine(e);
}
// Part3
try
{
using (StreamReader sr = new StreamReader(SavePath, ENCODE))
{
string result = "";
while (sr.EndOfStream != true)
result = result + sr.ReadLine() + "\n";
MessageBox.Show(result);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
But I find it strange that the process end at the place where Part2 complete, and the process directly end but didn't continue on Part3,
What's the reason to this condition? Generally the process should go through whole method but should not stop in the middle
(one more question)
And is there some other way can do the purpose of part2, and also can continue to part3 to comlplete whole method?
It could be because you are writing an async void method and you are calling some async methods in part 2. Try to change the async methods in part 2 to non-async methods:
using (StreamWriter sw = new StreamWriter(fs, ENCODE))
{
sw.Write(StrToSave);
sw.Flush(); // Non-async
sw.Close(); // Non-async
}
Does it behave as you expect now?
The problem is you are telling your app to await the methods, but never getting the Task result or a giving it a chance to complete. From what you've shown so far, you don't need the async stuff anyway, and greatly simplify the code:
public static void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE)
{
//Part1
try
{
MessageBox.Show(File.ReadAllText(SavePath, ENCODE));
}
catch (Exception e)
{
Console.WriteLine(e);
}
//Part2
try
{
File.WriteAllText(SavePath, StrToSave, ENCODE);
MessageBox.Show("Save");
}
catch (Exception e)
{
Console.WriteLine(e);
}
//Part3
try
{
MessageBox.Show(File.ReadAllText(SavePath, ENCODE));
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
If at all returning within try/catch/finally in not considered a structured programming how can I return from the below code block ?
public static string ReadFile()
{
StreamReader streamReader = null;
try
{
try
{
streamReader = new StreamReader(#"C:\Users\Chiranjib\Downloads\C# Sample Input Files\InputParam.txt"); //Usage of the Verbatim Literal
return streamReader.ReadToEnd();
}
catch (FileNotFoundException exfl)
{
string filepath = #"C:\Users\Chiranjib\Downloads\C# Sample Input Files\LogFiles.txt";
if (File.Exists(filepath))
{
StreamWriter sw = new StreamWriter(filepath);
sw.WriteLine("Item you are searching for {0} just threw an {1} error ", exfl.FileName, exfl.GetType().Name);
Console.WriteLine("Application stopped unexpectedly");
}
else
{
throw new FileNotFoundException("Log File not found", exfl);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return string.Empty;
}
//Code inside finally gets executed even if the catch block returns when an exception happens
finally
{
//Resource de-allocation happens here
if (streamReader != null)
{
streamReader.Close();
}
Console.WriteLine("Finally block executed");
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Log file not found ");
Console.WriteLine("Original exception " + ex.GetType().Name);
Console.WriteLine("Inner Exception " + ex.InnerException.GetType().Name);
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
Console.WriteLine("Finally block executed");
}
return streamReader.ReadToEnd() ?? string.Empty;
}
Thing is if I at all close the streamReader object before even getting it's value I would not be able to obtain a returned result.
But again it does not allow me to put a return in finally.
Please help me understand and overcome this difficulty in a standard way.
The easiest way for you to resolve this would be to just declare a variable inside your code and then read that out at the end.
For example.
public static string ReadFile()
{
var stringFile = "";
StreamReader streamReader = null;
try
{
try
{
streamReader = new StreamReader(#"C:\Users\Chiranjib\Downloads\C# Sample Input Files\InputParam.txt"); //Usage of the Verbatim Literal
stringFile = streamReader.ReadToEnd();
return stringFile
}
catch (FileNotFoundException exfl)
{
string filepath = #"C:\Users\Chiranjib\Downloads\C# Sample Input Files\LogFiles.txt";
if (File.Exists(filepath))
{
StreamWriter sw = new StreamWriter(filepath);
sw.WriteLine("Item you are searching for {0} just threw an {1} error ", exfl.FileName, exfl.GetType().Name);
Console.WriteLine("Application stopped unexpectedly");
}
else
{
throw new FileNotFoundException("Log File not found", exfl);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return string.Empty;
}
//Code inside finally gets executed even if the catch block returns when an exception happens
finally
{
//Resource de-allocation happens here
if (streamReader != null)
{
streamReader.Close();
}
Console.WriteLine("Finally block executed");
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Log file not found ");
Console.WriteLine("Original exception " + ex.GetType().Name);
Console.WriteLine("Inner Exception " + ex.InnerException.GetType().Name);
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
Console.WriteLine("Finally block executed");
}
return stringFile;
}
This should then read out your file by executing the following code
static void Main(string[] args)
{
var file = ReadFile();
Console.WriteLine(file);
Console.ReadLine();
}
I think you could eliminate several of those try/catch sequences and take care of disposing StreamWriter and StreamReader by using "using" statements. Here's an example:
using System;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var fileContents = ReadFile();
Console.ReadLine(); // cause program to pause at the end
}
public static string ReadFile()
{
try
{
using (var streamReader = new StreamReader(
#"C:\MyTestFile.txt"))
{
var fileContents = streamReader.ReadToEnd();
Console.WriteLine("File was read successfully");
return fileContents;
}
}
catch (FileNotFoundException fileNotFoundException)
{
LogReadFileException(fileNotFoundException);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
LogReadFileException(directoryNotFoundException);
}
catch (IOException ioException)
{
LogReadFileException(ioException);
}
// If we get here, an exception occurred
Console.WriteLine("File could not be read successfully");
return string.Empty;
}
private static void LogReadFileException(Exception exception)
{
string logFilePath = #"C:\MyLogFile.txt";
using (var streamWriter = new StreamWriter(logFilePath,
append: true))
{
var errorMessage = "Exception occurred: " +
exception.Message;
streamWriter.WriteLine(errorMessage);
Console.WriteLine(errorMessage);
}
}
}
}
I am having problem downloading files using Background transfer. After completion of download when moving file, it gives you an exception Operation not permitted
void addTransferRequest(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return;
string filePathToDownload = string.Empty;
filePathToDownload = activeReciter.DownloadURL;
filePathToDownload += fileName;
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload),
UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new
BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName,
UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
transferRequest.TransferStatusChanged +=
new EventHandler<BackgroundTransferEventArgs>
(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new
EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
try
{
BackgroundTransferService.Add(transferRequest);
chapterFileNames.Dequeue();
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
}
}
void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
{
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
using (IsolatedStorageFile isoStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
string filename = transfer.Tag;
string folderPath = string.Format(#"{0}{1}\{2}\",
DataSource.DOWNLOADLOCATION, activeReciter.ReciterID, chapter.ChapterID);
string fileFullPath = folderPath + filename;
if (!isoStore.DirectoryExists(Path.GetDirectoryName(folderPath)))
isoStore.CreateDirectory(Path.GetDirectoryName(folderPath));
if (isoStore.FileExists(fileFullPath))
isoStore.DeleteFile(fileFullPath);
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, fileFullPath);
//Excpetion is thrown here
RemoveTransferRequest(transfer.RequestId);
}
catch (Exception ex)
{
MessageBox.Show("Error Occured: " + ex.Message + transfer.Tag, "Error",
MessageBoxButton.OK);
return;
}
}
}
break;
}
}
When moving file, it throws exception, I don't know what is wrong with moving (this happens on some of the files not all files).
From the MSDN Page, under File System Restrictions section:
You can create any additional directory structure you choose
underneath the root “/shared/transfers” directory, and you can copy or
move files after the transfer is complete to ensure that the
background transfer service does not modify the files, but attempting
to initiate a transfer using a path outside of the “/shared/transfers”
directory will throw an exception.
Make sure you are not trying to move your file outside from the /Shared/Transfers folder.