I have no doubt that this questions are of very basic character but for me it's quite hard...
I want to select a filename/path with saveFileDialog.
Like this:
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
// Get file name.
string name = saveFileDialog1.FileName;
Source: http://www.dotnetperls.com/savefiledialog
Then I want to declare StreamWriter with the Path from above (suppose this works like this)
System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog1_FileOk.FileName);
This had to be done in the saveFileDialog1_FileOk function. Then I want to write to that file from another function/event handler (SerialPort has received data). And the filename should be able to change to a new file while runtime so that the data from the eventhandler
is written to another file.
But from that other function I'm not able to access the StreamWriter and I don't know how to change the file.
Also I would like to know how I can make the Data in the file accessable during runtime. In my first tests it's always written to the file when I call
file.Close()
b
ut then I cannot open it again.
It would be a great help if anyone could suggest me the way to go...
If I understood your question correctly; the approach you have selected seems to be violating the principle of single responsibility apart from causing you all those issues.
May be what you should consider doing is to create a class that manages the a static instance of stream and use it from open dialog and serial port events
Lets call the stream management class StreamManager. It would have an implementation similer to the following code
public class StreamManager
{
private static StreamWriter file = null;
public void NewFile(string filePath)
{
this.close();
file = new StreamWriter(filePath);
}
public void WriteToFile(string yourData)
{
file.Write(yourData);
}
public void close()
{
if (file != null /* and if not already been closed*/)
{
file.Flush();
file.Close();
}
}
}
Now you may call from new StreamManager().NewFile(fileName) open dialog and new StreamManager ().WriteToFile(…) from serial port.
Please note I have not tested the above code and provided only as a guide. You should add more state / error management to all methods
Cheers
Related
There is nothing wrong in the syntax of my code but whenever I try to run it keeps saying "The process cannot access the file because it is being used by another process". The only way I am running my application is my ending my application from the task manager. Please help me by explaining why this is happening and how to fix it.
private void btnLogin_Click(object sender, EventArgs e)
{
if (File.Exists("users.txt"))
{
string[] users = File.ReadAllLines("users.txt");
bool userFound = false;
foreach (string user in users)
{
string[] splitDetails = user.Split('~');
string username = splitDetails[1];
string password = splitDetails[2];
if ((txtBoxUsername.Text == username) && (txtBoxPassword.Text == password))
{
userFound = true;
break;
}
}
if (userFound)
{
Hide();
HomeForm home = new HomeForm();
home.Show();
}
else
{
MessageBox.Show("User details are incorrect",
"Incorrect details entered");
}
}
else
{
MessageBox.Show("No users have been registered", "No users");
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
Hide();
RegisterForm registerForm = new RegisterForm();
registerForm.Show();
}
This application is for my a level software systems development coursework and I am coding it in c#. I have only been learning c# for the past 5 months so I am still a beginner. I have already tried to find the answer to my problem in stack overflow and other websites.
I am expecting my application to launch when I press run, but instead I get a dialog box saying:
Error Unable to copy file "obj\Debug\SSD AS2 coursework.exe" to "bin\Debug\SSD AS2 coursework.exe". The process cannot access the file 'bin\Debug\SSD AS2 coursework.exe' because it is being used by another process.
SSD AS2 coursework
Check if you are closing all windows of your application when finalizing the app.
You must use Application.Exit() in any events that are going to finalize your application.
You can read more on the Documentation
It seems like the file you are trying to open is being used by another process try to close your text editor or another program writing to that file.
it is still possible to overcome the issue by using FileShare.ReadWrite and use the file from multiple processes, example on the following code:
FileStream fileStream = new FileStream("c:\users.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
StreamReader fileReader = new StreamReader(fileStream);
while (!fileReader.EndOfStream)
{
string user = fileReader.ReadLine();
string[] splitDetails = user.Split('~');
// the rest of the user logic in here...
}
fileReader.Close();
fileStream.Close();
I have an Error if I write something in a newly created File.
This is my code:
private void ButtonClick(object sender, EventArgs e)
{
Button b = (Button)sender;
string inputKey = b.Text;
for (int i = 0; i < tunes.Length; i++)
{
if (b.Text == tun[i].TuneName)
{
Console.Beep(tun[i].Frequency, 200);
Input.Items.Add(b.Text);
Output.Items.Add(tun[i].TuneName);
if (startButtonPressed == true)
{
filename2 = musicFileName + ".csv";
File.WriteAllText(filename2, tun[i].TuneName);
RecordList.Items.Add(tun[i].TuneName);
}
}
}
}
The Error comes at Line : File.WriteAllText()...
It says that the File can not be used, because it's used by an another process,but I havent opened any File.
I'd use a Filestream generated by File.Create(), but I'd make the loop inside the using statement, so you ensure that all ressources will be released at the end (that's why you use using).
using (FileStream fs = File.Create(Path.Combine(musicFileName, ".csv")))
{
foreach (tun in tunes)
{
fs.Write(tun.TuneName);
}
}
The problem you were actually having is, that you were never closing your file. You should look up using-keyword. It can used only with classes implementing the IDisponsable Interface. It then will call disponse() at the end of the using block and all ressources will be released, eg the file will be closed.
You need to make sure that the variable filename2 contains a valid path like C:\temp\myfile and not just myfile additionally you might need to run visual studio with elevated privilege if the location is not accessible otherwise.
You could also use streamwriter...
using (StreamWriter writer =new StreamWriter(musicFileName + ".csv";))
{
writer.Write(tun[i].TuneName);
}
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.
In this link, there is a code for "open recent files" and it seems that everybody understands whats going there except me. There are only a few lines to add the code and I dont understand below. Here what is FileOpenCore?? What should I replace for it?
RecentFileList.MenuClick += ( s, e ) => FileOpenCore( e.Filepath );
partial class RecentFileList
{
public void InsertFile( string filepath )
public void RemoveFile( string filepath )
}
I believe FileOpenCore is the name the author gave to the method that actually opens your files. Replace it with whatever method you have that takes a file name and opens it.
The InsertFile method is to be called (probably in your FileOpenCore) whenever a file is successfully opened. The RemoveFile should be called if you attempted to open a file and it failed. You don't want to keep files that no longer exist in your recent files list, for example.
So, if you defined your RecentFileList as the author did:
<common:RecentFileList x:Name="RecentFileList" />
And you hook up the click handler as he did in the constructor of your window:
RecentFileList.MenuClick += ( s, e ) => FileOpenCore( e.Filepath );
Your FileOpenCore (or whatever you want to call it) might look something like this (pseudo-code):
private void FileOpenCore(string filename)
{
try
{
// read your file
// and do whatever processing you need
// ...
// if open was successful
RecentFileList.InsertFile(filename);
}
catch (Exception e)
{
// opening the file failed - maybe it doesn't exist anymore
// or maybe it's corrupted
RecentFileList.RemoveFile(filename);
// Do whatever other error processing you want to do.
}
}
I am developing a c# application, backend as sqlite.In my application i have an option for clean databse.It means the curren .db file will delete using File.Delete method and again it create empty databse using File.create method.Now let me explain the problem.
To perform cleandatabse task, i have to stop all the process which is running ,after doing that if i click on clean database it is throwing an error that file cannot delete, it is being used by another process.i am able to stop all the thread which is running.
Somehow i am able to find which process is blocikng the file ,
foreach (var process in Process.GetProcesses()) {
var files = GetFilesLockedBy(process);
if (files.Contains(filePath))
{
procs.Add(process);
Console.WriteLine(process.ProcessName);
process.Kill();
File.Delete(filePath);
}
}
But in the above code i used process.Kill, which close the window form which i am running.
without using kill, i tried close and dispose which doesn't work for me.
Can you please help me to release the file from the process without closing the application and then yo delete the db file.
Thank you in advance
Best regards
Sangita.
You should make sure you close every stream you open it:
using (Stream str = File.Create("C:\\h.txt"))
{
// your code here
} // the stream will be automatically closed here
if you don't put this using statement, it will cause you a lot of bugs, even if you close it manually str.Close();
Streamss are disposable types, you must manage their lifetime manually, either by that using syntax, e.g.:
using (StreamReader f = new ...) {
}
... or by doing it more verbosely (this syntax is required if you allocate and delete the Stream in different code-blocks/functions):
try {
StreamReader f = new ...;
...
} finally {
if (null != f) f.Dispose();
}
... or by making the holding class an IDisposable by itself. See also What Your Mother Never Told You About Resource Deallocation.
Interestingly, this seems to be a practical incarnation of one of those https://stackoverflow.com/questions/2245196/c-urban-myths/2245382#2245382 :
0) In C++, you must mess around with pointers, that's old and dangerous, use C#
Gee, #include boost/shared_ptr> or one of the like. Actually, it is often easier to produce mess in your sowonderful C#:
static void Main () {
foo();
bar();
}
static void foo () {
var f = new StreamWriter ("hello.txt");
f.Write ("hello world");
}
static void bar () {
var f = new StreamReader ("hello.txt");
Console.WriteLine (f.ReadToEnd ());
}
"Unhandled IOException: The process cannot access the file 'hello.txt' because it is being used by another process."
Those claims, btw, are often made by those who happen to never have heard of RAII, and about how far you can get without even smart-pointers.
Not sure but you may be calling Kill on the current process.
EDIT : call Delte after the loop.
Try this :
int currentProcessId = Process.GetCurrentProcess().Id;
foreach (var process in Process.GetProcesses()) {
if (process.Id != currentProcessId)
{
var files = GetFilesLockedBy(process);
if (files.Contains(filePath))
{
procs.Add(process);
Console.WriteLine(process.ProcessName);
process.Kill();
}
}
}
File.Delete(filePath);
Moreover Close doesn't terminate the process, you have to call CloseMainWindow or Kill.