WriteAllText doesn't seem to get called [duplicate] - c#

This question already has answers here:
VS2010 does not show unhandled exception message in a WinForms Application on a 64-bit version of Windows
(5 answers)
Closed 9 years ago.
I am trying to save GetDirectories as a txt file, but somewhere my program fails.
private void Form1_Load(object sender, EventArgs e)
{
var directoryInfo = new System.IO.DirectoryInfo(#"g:\FTP\");
int directoryCount = directoryInfo.GetDirectories().Length;
...
var directoryInfo11 = new System.IO.DirectoryInfo(#"q:\FTP\");
int directoryCount11 = directoryInfo11.GetDirectories().Length;
int directoryCountMain = directoryCount + directoryCount2 +
directoryCount3 + directoryCount4 + directoryCount5 +
directoryCount6 + directoryCount7 + directoryCount8 +
directoryCount9 + directoryCount10 + directoryCount11;
string text = "Total Releases: ";
// WriteAllText creates a file, writes the specified string to the
// file, and then closes the file.
System.IO.File.WriteAllText(#"c:\test\ik.txt", text + directoryCountMain);
}
I don't get an error or anything, It looks like my code is skipped as I tried placing a MessageBox.Show below the code but It got ignored.

This won't solve your problem, but at least will shorten your code and make it maintainable. Replace your code with following, it will do the same.
var ftpDirs = new string[] { "g:/FTP/", ... };
int subDirsCount = 0;
foreach(var dir in ftpDirs)
{
subDirsCount += new DirectoryInfo(dir).GetDirectories().Length;
}
string text = "Total Releases: ";
File.WriteAllText(#"c:\test\ik.txt", string.Format("{0}{1}", text, subDirsCount));
Do not forget to add following at the top of the file.
using System.IO;

Place a breakpoint on the first statement in Form1_Load and see if it gets hit. If not, you probably need to subscribe to this event in your code.
If it gets hit, step through your code and find the line where it fails.
Note that Form_Load does not catch exceptions by default, so it will appear as though other lines were skipped. There are ways to solve it, just follow the above link.

I think this directories and path you have given doesnt exists or wrong therefore throwing exception when trying to get info
var directoryInfo11 = new System.IO.DirectoryInfo(#"q:\FTP\");
Add try catch block around your code and see if its throwing excpetion.

Related

Why am I unable to write to this file?

I wrote an Async method in C# to write to a file, however I keep on getting the following exception:
The process cannot access the file
'C:\XXX\XXX\XXX\XXX\EventBuffer.txt' because it is being used by
another process.
I've had a look at similar questions already posted on SO such as this one, and this one but it seems like the cause of my issue is different.
I used a process monitor to see which processes are trying to access the directory in which the file is in but the only process trying to access it is the one I'm debugging (Will post a snippet soon of the debug process window).
It isn't that file access was being attempted before it was closed upon last access, because I can get the exception when I attempt to access the file for the first time. I have tried to implement a delay after the StreamWriter is instantiated incase the write method was being attempted, I wasn't using the using block before and was disposing of the object using it's dispose methods but in one of the similar questions a this solved the issue.
public static async void UpdateEventBufferFile(EventDetails EventDtls)
{
string line;
try
{
using (StreamWriter EventBufferFile = new StreamWriter(FilePath, true)) // creates the file
{
//All barcode data space sperated for split detection
line = EventDtls.SiteID + " " + EventDtls.McID + " " + EventDtls.EventID + " "
+ EventDtls.EventDT + " " + EventDtls.AdditionalInfo;
await Task.Run(() => LogFileManager.SystematicLog(" Events " + line + " added to buffer file", " BufferFileWriter.cs"));
await EventBufferFile.WriteLineAsync(line); //no need for new line char WriteLine does that
await EventBufferFile.FlushAsync();
//The using block is suffice to dispose of the object the below is no longer required
//EventBufferFile.Dispose();
//EventBufferFile.Close();
//EventBufferFile = null;
}
}
catch (Exception ex)
{
}
}
I have near identical methods utilised within other classes that don't cause the same issue, which annoys me quite a bit.
The method is not being invoked from within a Loop. Invocation is done in a seprate static class in the method below:
public static void AddCentralEvents(int SiteID, int McID, int EventID, DateTime EventDT, string AdditionalInfo)
{
EventDetails EventDetailsObj = new EventDetails();
EventDetailsObj.SiteID = SiteID;
EventDetailsObj.McID = McID;
EventDetailsObj.EventID = EventID;
EventDetailsObj.EventDT = EventDT;
EventDetailsObj.AdditionalInfo = AdditionalInfo;
Task.Run(() => BufferFileWriter.UpdateEventBufferFile(EventDetailsObj));
}
The error is self explanatory, you are using an ASYNC method (in a loop perhaps) and while your first task hasn't completed it's run (i.e. written to the file) that's why you are ending up with that error.
Have you tried writing with a synchronized method? If you have a requirement to periodically write to a file (i.e. logging) use a logging framework.
I recommend using log4net It is 'one of the' the best out there.

Error: 'The process cannot access the file because it is being used by another process' in Visual Studio c#

I am having some trouble with this error in Visual Studio:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\aheij\Desktop\KinectOutput\swipe.txt' because it is being used by another process.
What I Have tried:
I have tried using these codes obtained from other solved StackOverflow questions similar to mine to try to solve the problem - but even that didn't seem to work?
Ive tried checking if the file is in use, but with no success.
I also run Visual Studio as administrator.
The file is not read-only.
The folder is not open, and the file is not being used in any other program when executing the code - at least not that I can see/know of.
The code:
So, to add some context to my code: I am writing some quick gesture detection code to the Kinect c# BodyBasics SDK v2 code freely available. This is a helper method that I added, that gets called in when a person is in view. If that person is executing the gesture, the method writes the frame time and gesture name to a text file.
Half the time, when the code does work, the gesture recognition works well. However, the other half of the time, the code breaks/stops because the writing to file bit causes the error.
Below is my code to see if the person is standing in the neutral position - its a bit waffly, so apologies about that. I have commented 'ERROR' where the error is (unsurprisingly):
private void Neutral_stance(VisualStyleElement.Tab.Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
CameraSpacePoint left_hand = joints[JointType.HandLeft].Position;
CameraSpacePoint left_elbow = joints[JointType.ElbowLeft].Position;
CameraSpacePoint left_shoulder = joints[JointType.ShoulderLeft].Position;
CameraSpacePoint left_hip = joints[JointType.HipLeft].Position;
CameraSpacePoint right_hand = joints[JointType.HandRight].Position;
CameraSpacePoint right_elbow = joints[JointType.ElbowRight].Position;
CameraSpacePoint right_shoulder = joints[JointType.ShoulderRight].Position;
CameraSpacePoint right_hip = joints[JointType.HipRight].Position;
double vertical_error = 0.15;
double shoulderhand_xrange_l = Math.Abs(left_hand.X - left_shoulder.X);
double shoulderhand_xrange_r = Math.Abs(right_hand.X - right_shoulder.X);
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_p = #"C:\Users\aheij\Desktop\KinectOutput\Punch.txt"; //write to punch file
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt"; //write to swipe file
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
File.AppendAllText(path_p, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
File.AppendAllText(path_p, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
}
}
}
Any solutions/ideas/suggestions to point me on the right track would be appreciated. I think that it would be good to use the 'using streamwriter' method as opposed to the method I am using here - but I am not sure how? Any help would be appreciated.
Additonal Info: Using Visual Studio 2015; Using windows 10.
Sidenote: I read somewhere that the Windows Search tool in Windows 10 can interfere and cause problems like this so I need to disable it?
As suggested to me I used the Filestream method & ensured the file was closed after use. But, even this still caused the same error.
Thus, I also got rid of having two file-writing actions in rapid succession of each other. I dont know if this is technically right or even true, but based off of this post here: link, my error could be coming up because I am trying to execute the second 'write to text file' line whilst the previous 'write to text file' line is still executing/writing to that same folder & location - hence the clash? Please someone, correct me if I am wrong.
Either way, this seems to have worked.
See below for my edited/corrected method:
private void Neutral_stance(Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
//cameraspace point joint stuff here again (see original post for this bit leading up to the if statements.)
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt";
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
FileStream fs_s = new FileStream(path_s, FileMode.Append); //swipe
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Neutral" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
FileStream fs_s = new FileStream(path_s, FileMode.Append);
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Unknown" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
Do let me know if there is any way I can make this more elegant or anything else I should be aware of w.r.t this answer.
The code is based off of the code found here: FileStream Tutorial website

C#: System.Windows.Forms.SendKeys.SendWait does not work with the path as input

Here is my code
private string path = Path.GetTempPath() + "Test.pdf";
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
System.Windows.Forms.SendKeys.SendWait(path);
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
Keyboard.SendKeys("{Enter}");
There is a window explorer for opening a file. The file exists on the temp path. It sometimes works and sometimes it enter the path as :\Users\.... which means it ignores C. I am not sure what is the problem? Why it is inconsistent? Any help is appreciated.
I already tried
private string path = #"" + Path.GetTempPath() + "Test.pdf";
but it is the same (sometimes works, sometimes does not)
I added empty char before the path
private string path = #" " + Path.GetTempPath() + "Test.pdf";
But still it is the same!
I had a similar problem with Coded UI but it omitted a small number of characters randomly throughout the string. I never found out the real reason, but I got around the problem by sending the characters one at a time with a short pause between them. I use code similar to the following:
void SendKeysSlowly(string text)
{
foreach ( char s in text )
{
SendKeys(s); // Choose the appropriate send routine
System.Threading.Thread.Sleep(50); // Milliseconds, adjust as needed
}
}
Also, you should ensure the string always starts with a "C:"? You could add code of the form Assert(path.StartsWith("C:\\")); before the first ...Sendkeys call.
Try using
Path.Combine(Path.GetTempPath(), "Test.pdf")

File.ReadAllText prevents Form from closing on x button click

I have a weird problem. I want to write the visible textBox.Text to an "ini" file on FormClosing (right before the form shuts down), so I double clicked that event under the main form's Properties panel and filled the associated function as follows:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// store the whole content in a string
string settingsContent = File.ReadAllText(settingsPath + "CBSettings");
// replace a name with another name, which truly exists in the ini file
settingsContent.Replace(userName, userNameBox.Text);
// write and save the altered content back to the ini file
// settingsPath looks like this #"C:\pathToSettings\settingsFolder\"
File.WriteAllText(settingsPath + "CBSettings", settingsContent);
}
The form starts up without a problem, but it won't quit by clicking the x button. It only closes correctly when I comment the File.WriteAllText line out. If I just stop debugging, the files content doesn't change either.
EDIT :
The actual problem was the function which I used to find and return the userName from the ini file:
public static string GetTextAfterTextFromTextfile(string path, string file, string fileExtension, string textToLookFor)
{
string stringHolder;
StreamReader sr = File.OpenText(path + file + fileExtension);
while((stringHolder = sr.ReadLine()) != null)
{
if(stringHolder.Contains(textToLookFor))
{
return stringHolder.Replace(textToLookFor, "");
}
}
sr.Close();
return "Nothing found";
}
The content of the ini file:
User Name = SomeName
Bot Name = SomeName
I copied the above function from stackoverflow. I was sure that it worked because it captured 'SomeName' just as I wanted. Now I use another function (also from stackoverflow), that searches the ini file for 'User Name = ' and returns the text that comes right after it.
public static string GetTextAfterTextFromTextfile(string path, string textToSkip)
{
string str = File.ReadAllText(path);
string result = str.Substring(str.IndexOf(textToSkip) + textToSkip.Length);
return result;
}
The problem is, that it returns
SomeNameBot Name = SomeName
Any hint on how to limit string result to only one line? Many thanks in advance!
This is a normal mishap on the 64-bit version of Windows 7, caused by a nasty flaw in that operating system's Wow64 emulator. Not limited to Winforms apps, C++ and WPF apps are affected as well. For .NET apps, this only misbehaves if a debugger is attached. Repro code:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
throw new Exception("You will not see this");
}
The debugger won't stop when the exception is thrown and you can't close the window anymore. I wrote a more extensive answer about this problem, including recommended workarounds, in this post.
Quick fix in your case: use Debug + Exceptions, tick the Thrown checkbox. The debugger now stops when the exception is thrown, allowing you to diagnose and fix your bug.

file loading error

Okay so i'm trying to load up a bunch of profiles through C# and I keep getting this error when I try to start up the program.
C:\C#FILES>program.exe
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
at ConsoleApplication2.Program.loadAccounts()
at ConsoleApplication2.Program.Main(String[] args)
C:\C#FILES>
i've investigated and i think it has to do with the format of the accounts in the file
i'm wondering what the proper way is, i've tried every way i can think of
here's the loading accounts method
private static void loadAccounts()
{
using (TextReader tr = new StreamReader("accounts.txt"))
{
string line = null;
while ((line = tr.ReadLine()) != null)
{
String[] details = line.Split('\t');
accounts.Add(details[0] + ":" + details[1]);
}
}
}
the accounts.txt part is the part i'm unsure about, i thought it would be as follows
username(tab)password
like this
username password
however it gives the error shown above
does anyone know what the proper account format should be?
You're getting an IndexOutOfRangeException, which suggests that details only had a single entry - which means there wasn't a tab on that line.
I suggest you print out the line in question before splitting, so you can see which line is causing problems. Or possibly do it conditionally:
while ((line = tr.ReadLine()) != null)
{
String[] details = line.Split('\t');
if (details.Length == 1)
{
// Or log it, or whatever...
Console.WriteLine("Input error: no tab in line '{0}'", line);
}
else
{
accounts.Add(details[0] + ":" + details[1]);
}
}
This is occurring because the line you are splitting from your input does not contain the elements requested.
It is unlikely that the first (read: 0th) element in the array is the cause of the issue because of the way that .NET deals with Split.
Have you check that there are no blank lines in your input file? A single blank line (even at the end of the file) would cause this issue.
There are multiple checks you could add such as..
if(!string.IsNullOrWhitespace(line)) ...
or
if(details.Length > 1)
These are a few checks, either or both I would recommend implementing (there are more to consider) otherwise you are just blindly trusting input values and that is not good practice in general.

Categories

Resources