C# Read Write TextFile End In The Middle - c#

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);
}
}

Related

c# UWP ReadTextAsync fails at 2 time

So i'm trying to import 2 configs from the localfolder with Windows.Storage. But at the second time it fails with no exception.
This is my Code:
public async Task<string> ImportLines(string filename)
{
try
{
Windows.Storage.StorageFile importFile = await StorageFolder.GetFileAsync(filename);
string savedString = await Windows.Storage.FileIO.ReadTextAsync(importFile);
return savedString;
}
catch (Exception)
{
//log
}
}
I call this methode with:
public async void LoadConfig()
{
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + PluginsFilename))
{
string tmp = await _textDataHandler.ImportLines(PluginsFilename);
Plugins = JsonConvert.DeserializeObject<PluginConfiguration>(tmp);
}
else
{
CreateDefaultPluginsConfiguration();
//log
_textDataHandler.CreateFile(_pluginsFilename);
string export = JsonConvert.SerializeObject(Plugins, Formatting.Indented);
_textDataHandler.ExportText(_pluginsFilename, export);
//log
}
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + _settingsFilename))
{
string tmp = await _textDataHandler.ImportLines(Settingsfilename);
Config = JsonConvert.DeserializeObject<Configuration>(tmp);
_textDataHandler.CreateFile(Config.DatabaseFilename);
}
else
{
CreateDefaultSettingsConfiguration();
//log
_textDataHandler.CreateFile(_settingsFilename);
string export = JsonConvert.SerializeObject(Config, Formatting.Indented);
_textDataHandler.ExportText(_settingsFilename, export);
//Log
}
}
If one config does not exist its fine but if both exist it fails at the second time
If you have created async method. please avoid synchronous invoke with GetResult. You could add await key word in front of calling line.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string tmp = await ImportLines(Filename);
}
Update
Please try use dataReader to read file content.
public async Task<string> ImportLines(string filename)
{
try
{
StorageFile importFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var buffer = await FileIO.ReadBufferAsync(importFile);
using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
{
return dataReader.ReadString(buffer.Length);
}
}
catch (Exception ex)
{
return ex.Message;
}
}

MS Cognitive Face API: Unable to detect faces

I am trying to use Microsoft Cognitive Face API for the first time. Documentation gives quite a simple method to detect face from memory stream. I am trying to detect faces from images located inside a folder. Right now there is only one image inside the folder. The issue is whenever the control reaches the following line:
var faces = await faceServiceClient.DetectAsync(memStream, true, true);
it terminates without any exception or error. Here is the complete code I have written.
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Common;
using Microsoft.ProjectOxford.Face.Contract;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FaceDetection.FaceDetect
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Face Detect";
Start();
}
static async Task Stop()
{
await Close();
}
private static Task Close()
{
return Task.Run(() =>
{
Environment.Exit(0);
});
}
static async Task ReStart(string _reason = "")
{
Console.WriteLine(_reason + "To restart the process press 'R'. To exit press 'X'");
var _response = Console.ReadLine();
if (_response == "r" || _response == "R")
await Start();
else
await Stop();
}
static async Task Start()
{
Console.Clear();
Console.WriteLine("Enter Folder Path");
string imageFolderPath = Console.ReadLine();
if (!Directory.Exists(imageFolderPath))
{
await ReStart("Folder does not exist! ");
}
else
{
await SaveFiles(imageFolderPath);
}
}
static async Task SaveFiles(string imageFolderPath)
{
try
{
DirectoryInfo dInfo = new DirectoryInfo(imageFolderPath);
string[] extensions = new[] { ".jpg", ".jpeg" };
FileInfo[] files = dInfo.GetFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
if (files.Length == 0)
await ReStart("No files found in the specified folder! ");
else
{
string subscriptionKey = "ADSFASDFASDFASDFASDFASDFASDF";
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["subscriptionKey"]))
subscriptionKey = ConfigurationManager.AppSettings["subscriptionKey"].ToString();
//var stringFaceAttributeType = new List<FaceAttributeType> { FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.Gender, FaceAttributeType.Age };
//IEnumerable<FaceAttributeType> returnFaceAttributes = stringFaceAttributeType;
IFaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey);
foreach (FileInfo file in files)
{
try
{
using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
//Used following commented code to make sure MemoryStream is not corrupted.
//FileStream _file = new FileStream(imageFolderPath + "\\test.jpg", FileMode.Create, FileAccess.Write);
//memStream.WriteTo(_file);
//_file.Close();
//memStream.Close();
try
{
//This line never returns a result. The execution terminates without any exception/error.
var faces = await faceServiceClient.DetectAsync(memStream, true, true);
if (faces != null)
{
foreach (var face in faces)
{
var rect = face.FaceRectangle;
var landmarks = face.FaceLandmarks;
}
}
else
Console.WriteLine("No face found in image: " + file.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
}
catch (Exception ex)
{
Console.WriteLine("There was an error!");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("There was an error!");
}
await ReStart();
}
}
}
Can someone point out what am I missing. Why is this code not working?
When you read the file in to the MemoryStream, your read pointer is advanced to the end. So memStream passed in to DetectAsync() appears empty. The fact is you need not copy your file to memory. You could simply pass in the FileStream after opening.
using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
{
try
{
var faces = await faceServiceClient.DetectAsync(fileStream, true, true);
if (faces != null)
{
foreach (var face in faces)
{
var rect = face.FaceRectangle;
var landmarks = face.FaceLandmarks;
}
}
else
{
Console.WriteLine("No face found in image: " + file.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
Alternatively, you can rewind the memory stream by setting memStream.Position = 0 before calling DetectAsync.

how to return from try/catch/finally in C# ?

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);
}
}
}
}

Is there a "nuclear option" for closing/freeing a file?

My original related question here (https://stackoverflow.com/questions/17332403/is-there-such-a-c-sharp-method-or-methodology-that-would-equate-to-filealready) was marked as a duplicate, and I used the supposed duplicate
(Is there a way to check if a file is in use?) to try to solve my problem, but I'm still getting flooded with Null Reference Exceptions on some file I/O operations.
Based on that halcyon post of yore, I altered the previous code from this:
public FileQuickRead(string filename)
{
try
{
SR = File.OpenText(filename);
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileQuickRead");
}
. . .
...to this:
public FileQuickRead(string filename)
{
// Added 6/27/2013; adapted from https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
try
{
using (Stream stream = new FileStream(filename, FileMode.Open))
{
try
{
SR = File.OpenText(filename);
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileQuickRead");
}
}
}
catch (Exception exc)
{
// If the "using Stream filename" fails
#if TRACE
UtilCE.LogInfo.Add2LogFile(string.Format("Catch block in FileQuickRead caught: {0}", exc.Message));
#endif
}
}
...The log file never contains the "Catch Block" string, so it's getting past the "using filename" but apparently failing on the call to File.OpenText().
Also, it's failing on the other two methods in the class, namely ReadLn and FileClose:
public string FileReadLn()
{
try
{
aLine = SR.ReadLine();
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileReadLn");
}
return aLine;
}
public void FileClose()
{
try
{
SR.Close();
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileClose");
}
}
I get a NullReferenceException on FileQuickRead, FileReadLn, then FileClose, three times in succession.
The only other thing in the class are these global declarations:
private StreamReader SR;
private string aLine;
Callers do so in this way:
fileQuickRead = new FileQuickRead(fn);
// Read the line from the file*
aLine = fileQuickRead.FileReadLn();
. . .
while ((aLine != null) && (aLine != ""))
. . .
aLine = fileQuickRead.FileReadLn();
if (aLine == null)
continue;
. . .
finally
{
fileQuickRead.FileClose();
}
Is the SR.Close() in the FileClose() method not enough? Do I need to do something to completely flush the file, or...???
Great - the only comment in the whole project, and it only divulges the achingly obvious.

Opening text file in c#

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!

Categories