Wait for previous function to complete - c#

I'm working on a web installer and one of the things I have currently is
void MoveFiles()
{
lbldlstatus.Text = "Moving Files";
string InstallDirectory = Directory.GetCurrentDirectory() + "/DoxramosRepack-master";
DirectoryInfo d = new DirectoryInfo(InstallDirectory);
foreach(var file in d.GetFiles("*"))
{
try
{
if (File.Exists(file.Name)) {
File.Delete(file.Name);
}
Directory.Move(file.FullName, file.Name);
Cleanup();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
}
void Cleanup()
{
lbldlstatus.Text = "Cleaning Up Files";
try
{
if (File.Exists("Repack.zip"))
{
File.Delete("Repack.zip");
}
if(Directory.Exists("DoxramosRepack-master"))
{
Directory.Delete("DoxramosRepack-master");
}
lbldlstatus.Text = "Repack Installed Successfully";
}
When I get to Cleanup() I have a System.IO.IOException.
Process cannot access the file Repack.zip because it being used by
another process.
The full code runs
Download->Extract->Move->Cleanup.
I'm not sure what process is being used, but I'm looking to find a way for each process to wait for the previous to finish before starting.

According to extract code below
void Extract()
{
string zipPath = #"Repack.zip";
string extractPath = #".";
try
{
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
MoveFiles();
}
}
catch (ZipException e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
You are calling the move files before you are finish with the zip file. Seeing as the move file method is responsible for calling the clean up function then you should make sure that the zip file is already disposed of before trying to delete it.
void Extract()
{
string zipPath = #"Repack.zip";
string extractPath = #".";
try
{
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
}
MoveFiles();
}
catch (ZipException e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
Clean up should also be called after everything has been moved. Currently the example code is calling it repeatedly in the for loop.

The code which you pasted on pastebin is different from what you have posted here. The code in pastebin never calls cleanup.
Anyways the problem is because you are calling MoveFiles() from within the using block here:
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
MoveFiles();
}
Move it outside the using block.

Related

Can't Read CSV from Download Folder in Android Device C# Unity

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.

Write all of the processes to a text file

I am trying to write all of the processes to a text file, but it will only write the first process in my system. Would you guys mind seeing if there is anything wrong or that I can adjust to fix this issue?
private void button5_Click(object sender, EventArgs e)
{
try
{
var ap = Process.GetProcesses();
SaveFileDialog sfdv2 = new SaveFileDialog();
if(sfdv2.ShowDialog() == DialogResult.OK)
{
foreach(Process process in ap)
{
string path = sfdv2.FileName;
BinaryWriter bw2 = new BinaryWriter(File.Create(path));
bw2.Write("test" + " " + ap.ToString());
bw2.Dispose();
}
}
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
}
Take a step back and see what you are writing.
For each process in the list, you create a file with the same name (and overwrite the previous one) and write "test {process}" in it.
The code does what you tell it, and that's why you end up with only one process in the file.
You can fix this by opening the file outside the loop and closing it afterwards, or even better, you can write it with a using statement. Also, please don't use BinaryWriter for writing to text file. There are many other methods, and the suggested one is StreamWriter. Take a look at this documentation page to see some examples.
string path = sfdv2.FileName;
// with using, the file will be also closed when it's disposed.
using (var file = new System.IO.StreamWriter(path))
{
foreach(Process process in ap)
{
file.WriteLine("test " + ap.ToString());
}
}
You may wish to consider using the Async version of the button click event handler. This is because writing to files is potentially a long running process. So you might want to start it and not wait to block your UI. Combine this with StreamWriter.WriteAsync methods and use in conjunction with await.
e.g.
private async void button5_Click(object sender, EventArgs e)
{
try
{
var ap = Process.GetProcesses();
SaveFileDialog sfdv2 = new SaveFileDialog();
if(sfdv2.ShowDialog() == DialogResult.OK)
{
string path = sfdv2.FileName;
using(StreamWriter bw2 = new StreamWriter(File.Create(path)))
{
foreach(Process process in ap)
{
await bw2.WriteAsync("test" + " " + process.ProcessName.ToString());
}
}
}
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
}
Try splitting the initial problem into smaller, easier tasks:
Lines we want to write down:
var linesToWrite = Process
.GetProcesses()
.Select(process => $"test {process.ProcessName}");
UI:
using (SaveFileDialog dialog = new SaveFileDialog() {
//TODO: here we put dialog's parameters
}) {
if (dialog.ShowDialog() == DialogResult.OK) {
//TODO: here we put the main routine
}
}
Combining it all together:
private void button5_Click(object sender, EventArgs e) {
using (SaveFileDialog dialog = new SaveFileDialog() {
//TODO: here we put dialog's parameters
}) {
if (dialog.ShowDialog() == DialogResult.OK) {
File.WriteAllLines(dialog.FileName, Process
.GetProcesses()
.Select(process => $"test {process.ProcessName}"));
}
}
}

FileSystemWatcher C# - cannot access file because it is being used by another process

I'm using FileSystemWatcher to detect directory changes, and after that I read file content and insert it to database.
Here's my code:
private FileSystemWatcher _watcher;
public MainWindow()
{
try
{
InitializeComponent();
GetFiles();
//Task.Factory.StartNew(() => GetFiles())
// .ContinueWith(task =>
// {
// }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
catch(Exception ex)
{
//..
}
}
public bool GetFiles()
{
_watcher = new FileSystemWatcher(Globals.iniFilesPath, "*.ini");
_watcher.Created += FileCreated;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
private void FileCreated(object sender, FileSystemEventArgs e)
{
try
{
string fileName = Path.GetFileNameWithoutExtension(e.FullPath);
if (!String.IsNullOrEmpty(fileName))
{
string[] content = File.ReadAllLines(e.FullPath);
string[] newStringArray = content.Select(s => s.Substring(s.LastIndexOf('=') + 1)).ToArray();
ChargingStationFile csf = new Product
{
Quantity = Convert.ToDecimal(newStringArray[1]),
Amount = Convert.ToDecimal(newStringArray[2]),
Price = Convert.ToDecimal(newStringArray[3]),
FileName = fileName
};
ProductController.Instance.Save(csf);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If I run this code with CTRL+F5 I received this message:
But If I go with F5 (Debugging mode) than I receive this and not this error about cannot access process and item is sucessfully saved. This is confusing me really..
Should I dispose watcher? or something like that? Maybe I'm missing something here?
This is first time I'm using FileSystemWatcher, obliviously something is really wrong here..
P.S I've found out that this line is causing an exception:
string[] content = File.ReadAllLines(e.FullPath);
how come?
Thanks guys
Cheers
File.ReadAllLines() cannot access the file when it is open for writing in another application but you can use a FileStream and StreamReader instead.
Replace string[] content = File.ReadAllLines(e.FullPath); with the following code and you should be able to read the contents of the file regardless of whether it is open in another application:
List<string> content = new List<string>();
using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader sr = new StreamReader(stream))
{
while (!sr.EndOfStream)
content.Add(sr.ReadLine());
}
As mention in this answer:
Most likely what is happening here is that the FileCreated event is
being raised and tries to process the file before is has been
completely written to disk.
So, you need to wait until the file has finished to copy. According to this other answer:
From the documentation for FileSystemWatcher:
The OnCreated event is raised as soon as a file is created. If a file
is being copied or transferred into a watched directory, the OnCreated
event will be raised immediately, followed by one or more OnChanged
events.
So, a workaround for your case will be to create a list of strings containing the paths of the files that could not be read in the Created method handler, and re-process those paths in the Changed event of the FileSystemWatcher (read the comments in the code) :
public partial class MainWindow : Window {
private FileSystemWatcher _watcher;
public MainWindow() {
try {
InitializeComponent();
GetFiles();
} catch (Exception ex) {
MessageBox.Show($"Exception: {ex.Message}");
}
}
private bool GetFiles() {
_watcher = new FileSystemWatcher(#"C:\TestFolder", "*.ini");
_watcher.Created += FileCreated;
_watcher.Changed += FileChanged; // add this.
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
// this field is new, and contains the paths of the files that could not be read in the Created method handler.
private readonly IList<string> _waitingForClose = new List<string>();
private void FileChanged(object sender, FileSystemEventArgs e) {
if (_waitingForClose.Contains(e.FullPath)) {
try {
string[] content = File.ReadAllLines(e.FullPath);
string[] newStringArray = content.Select(s => s.Substring(s.LastIndexOf('=') + 1)).ToArray();
MessageBox.Show($"On FileChanged: {string.Join(" --- ", newStringArray)}");
// Again, process the data from the file to saving in the database.
// removing the path, so as not to reprocess the file..
_waitingForClose.Remove(e.FullPath);
} catch (Exception ex) {
MessageBox.Show($"Exception on FileChanged: {ex.Message} - {e.FullPath}");
}
}
}
private void FileCreated(object sender, FileSystemEventArgs e) {
try {
string fileName = Path.GetFileNameWithoutExtension(e.FullPath);
if (!String.IsNullOrEmpty(fileName)) {
string[] content = File.ReadAllLines(e.FullPath);
string[] newStringArray = content.Select(s => s.Substring(s.LastIndexOf('=') + 1)).ToArray();
MessageBox.Show($"On FileCreated: {string.Join(" --- ", newStringArray)}");
// process the data from the file to saving in the database.
}
} catch (Exception ex) {
// if the method fails, add the path to the _waitingForClose variable
_waitingForClose.Add(e.FullPath);
//MessageBox.Show($"Exception on FIleCreated: {ex.Message} - {e.FullPath}");
}
}
}

BackgroundTransfer cannot move files

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.

Delete file using C# Thread

I was reading this article (Can't delete a file using threads) about my problem but things are getting difficult to me.
My problem is really simple, I just want to delete this old file, if I start the method "dlMoveNovaVersao" normally the file is deleted but if I put this on a thread (like bellow) I got "You are not allow". Someone knows what's the problem? (I wanna use thread).
private void verificaVersaoSupervisor_Tick(object sender, EventArgs e)
{
Thread threadConexao = new Thread(threadVerificaConexao);
threadConexao.Start();
}
public void threadVerificaConexao()
{
try
{
Dns.GetHostEntry("www.google.com.br");
if (verificaVersao())
{
try
{
verificaKillSupervisor();
dlMoveNovaVersao();
Application.Exit();
}
catch (Exception)
{ }
}
else
{
Application.Exit();
}
}
catch (Exception)
{ }
}
public void dlMoveNovaVersao()
{
WebClient webClient = new WebClient();
webClient.DownloadFile("Anywebsite", #"c:\temp\supervisor.exe);
try
{
File.Delete(#"c:\Test\supervisor.exe); //This file is always there!
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Just discribe the purpose, My program (Supervisor Starter) check on website if I have an old version of "Supervisor" running (using XML), If it's true my "Supervisor Starter" verify if there is a process called "Supervisor" running and kill it after that "Supervisor Starter" download the new version and run it. (The program is small and the update don't take more then 4 seconds).
The problem start when my "Supervisor Starter" try delete the old version of my program. If I use thread I receive "I haven't permission to access the file", if I use the same method on Form class the file is deleted.
I suspect that you're running the thread while the file is in use. When the thread runs, it runs in parallel with the current thread. Have you ensured that that file is closed?.
Otherwise I think that the thread maybe being created with a credentials that are not yours. But I'm pretty sure this is not the case.
See if this is different for each case
catch (Exception err)
{
MessageBox.Show("User {0}. Message {1}",
System.Security.Principal.WindowsIdentity.GetCurrent().Name,
err.Message);
}
This is my functions for deleting files in threads if the files are in used
private static void Delete(System.IO.FileInfo file)
{
if (file.Exists)
{
int Attempt = 0;
bool ShouldStop = false;
while (!ShouldStop)
{
if (CanDelete(file))
{
file.Delete();
ShouldStop = true;
}
else if (Attempt >= 3)
{
ShouldStop = true;
}
else
{
// wait one sec
System.Threading.Thread.Sleep(1000);
}
Attempt++;
}
}
}
private static bool CanDelete(System.IO.FileInfo file)
{
try
{
//Just opening the file as open/create
using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate))
{
//If required we can check for read/write by using fs.CanRead or fs.CanWrite
}
return false;
}
catch (IOException ex)
{
//check if message is for a File IO
string __message = ex.Message.ToString();
if (__message.Contains("The process cannot access the file"))
return true;
else
throw;
}
}

Categories