How to delete file from isolated Storage - c#

I am trying to delete files from isolated storage. But it returning error message to me. I don't know where i did mistake.
public void Delete(string folder, string fileName)
{
try
{
string path = folder + "\\" + fileName + ".txt";
string delPath = folder + "/" + fileName + ".txt";
MessageBox.Show(delPath);
if (myIsolatedStorage.DirectoryExists(folder))
{
if (myIsolatedStorage.FileExists(delPath))
{
myIsolatedStorage.DeleteFile(delPath);
MessageBox.Show("File is Deleted..!!");
}
else
MessageBox.Show("There is no file is exists");
}
else
{
MessageBox.Show("There is no Folder is exists");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please let me know where i did mistake.
Thanks in advance..
Error message:-

Perhaps, the file, you're trying to delete, is still in usage. Your application should have no open files or references to files that you are trying to delete.

Related

Skipping a file which is using by another process

I am creating a C# application. This app is deleting temporary folders. But some processes are being used. That's why it can't remove them. And i have to skip those files. I hope you can help.
Code:
// Clearing folder's content (\)
void ClearFolder(string FolderName)
{
try
{
if (Directory.Exists(FolderName))
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
fi.IsReadOnly = false;
fi.Delete();
CleanLog.Items.Add(fi.FullName + " " + "is found and deleted");
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
di.Delete();
CleanLog.Items.Add(di.FullName + " " + "is found and deleted");
}
}
else
{
CleanLog.Items.Add(FolderName + " " + "is not found.");
}
}
catch (Exception Error)
{
MessageBox.Show(Error.Message, "Error", MessageBoxButtons.OK);
}
}
// Clearing folder's content (\)
private void Clean_MouseDown(object sender, MouseEventArgs e)
{
// Folder Locations
string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + #"\Temp"; // Temp
string Temp2 = Path.GetTempPath(); // %Temp%
// Folder Locations
// Clearing folders
ClearFolder(Temp);
ClearFolder(Temp2);
// Clearing folders
}
To achieve this, you can also use try catch for the delete statement like
try
{
fi.Delete();
}
catch
{
//Your message...
}

Creating a new directory for log event file in windows service in c#

I am wondering on how to create a new directory for a log event file in windows service through c#
I have the following code:
public static void WriteLog(string Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);
//sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.WriteLine(Message);
sw.Flush();
sw.Close();
}
catch{}
}
As the docuemtation states for the Directory.CreateDirectory(path):
Creates all directories and subdirectories in the specified path unless they already exist.
Modified from the example source code:
string path = #"c:\MyDir";
try
{
// Try to create the directory.
Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
There is a really great tutorial on dotnetperls containing example code, exceptions, tips and other useful information about creating directories!
Look up that SO-question to create folders inside the same directory your executable has started, or simple use relative paths instead of absolute ones:
Directory.CreateDirectory("Test");
That way you will never have conflicts about finding the correct path!
File yourFolder= new File("C:/yourFolder");
// if the directory does not exist, create it
if (!yourFolder.exists()) {
System.out.println("Creando directorio: " + yourFolder.getName());
boolean result = false;
try
{
yourFolder.mkdir();
result = true;
}
catch(SecurityException se){
}
if(result) {
System.out.println("Folder created");
}
}

How to open excel file's read only mode on C#?

I'm creating dataset from csv excel file and that files is processing while I access it.
It says "
I need to access it read only mode? This is working code.
private void connect()
{
try
{
if (checkbox1.Checked == false)
{
FilePath = #"C:\FILE";
}
else
{
FilePath = #"\\192.168.0.2\file\"; //
}
strConn = #"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + FilePath + #"\;Extensions=csv,txt";
Connect = new OdbcConnection(strConn);
Connect.Open();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
DataGrid1.SelectAll();
DataGrid1.ClearSelection();
FileName = ".csv";
CSVDataSource = FilePath + FileName;
ReadData(FileName);
DataGrid1.Update();
}
It says it cannot open the file '(unknown)'. The thing about exclusive and permissions is probably just a too general error description. You do not seem to have a valid file path, also you might not be able to open it directly from a network path.
Verify your file path, and if it still not works - copy it to your local machine and try again.

How to create a folder then save an image to the created folder using fileuploader in C# asp.net?

I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}

To delete a desk top file in asp.net c#

i want a solution for this , i want to delete a file which is residing in my desk top using asp.net c# , i used below code:
try
{
FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + FileNameTextBox.Text);
if (TheFile.Exists)
{
File.Delete(MapPath(".") + "\\" + FileNameTextBox.Text);
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
lblStatus.Text += ex.Message;
}
catch (Exception ex)
{
lblStatus.Text += ex.Message;
}
but it always says the file location cannot be found , please help me
thanks in advance `
If you are trying to delete a user's desktop file using an asp .net page you cannot do it. The code executes on the server side and the path will access to the desktop of the server that your application is being hosted.
I would try doing it this way instead:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
File.Delete(Path.Combine(desktopPath, "filetobedeleted"));

Categories