Please tell me why file.Delete(gpath) is not working?
i will be very thankful to you :) If there is any error on this code then tell about that error.This code can be wrong so please tell me.
string gpath;
string path=#"c:\Users\Adam\Desktop\";
string name="file";
string f="";
int i=0;
string ext=".txt";
while(File.Exists(path + name + f + ext))
{
i++;
f = i.ToString();
}
gpath = path + name + f + ext;
button2.Enabled = true;
File.Create(gpath);
File.Delete(gpath);//why there is an Error??
File.Create returns a FileStream which you haven't disposed of, so there's an open handle to the file. When you try and delete a file with that has a handle attached to it, you'll get an error saying that the file is in use.
I don't know why you're trying to delete the file straight after creating it so if you explain what you're ultimately attempting to do, there's likely a better way of going about it.
Related
I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.
Just a quick question if you can help me, please.
In C#, I am creating a directory, if it does not exist. In the next command, I am checking if the directory exists, I will copy some files.
The Problem is, to creating a new directory or Deleting it, takes time and slower than next code execution time.
The software gives an error of "The folder does not exist ".
I used Thread.Sleep(5000); to wait 5 seconds before copying the content to the directory.
It seems to be working but I feel like that this is not how it's supposed to be done. Does anyone know better coding?
string logDirectoryPath = Directory.GetCurrentDirectory() + "\\LogFiles";
if (!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
Thread.Sleep(5000);
}
if (Directory.Exists(Directory.GetCurrentDirectory() + "\\LogFiles"))
{
var s = logDirectoryPath + "\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(s))
{
w.WriteLine("--");
w.Write("\r\nLog Entry : ");
w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
}
}
//EDIT
JUST thought maybe I should use a loop?
While(!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
}
Use DirectoryInfo
DirectoryInfo di = new DirectoryInfo(#{PATHSTRING});
and use di.Exists to check it exists / di.Create() to create folder
and I'd like to recommend to use logDirectoryPath which you defined already.
like this
DirectoryInfo di = new DirectoryInfo(logDirectoryPath);
if ( !di.Exists ) {
di.Create();
}
As an unexperienced developer I have no idea whether this question is phrased properly (I did check the internet but I havent found a solution that worked for me that is why I signed up here). I am trying to make a form where users can upload files to attach to their form (in SharePoint 2013) and I used the following code as an example. The idea is to temporary accept the files and display them to the user and upload them to the document library when the form is submitted.
In my code however, this results in "acces denied" and when I debugged it, the following piece of my code seemed to be causing the problem:
public void BtnAttachmentUpload_Click(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
if (fileName != "")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (FileUpload.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + "\\" + _newfilePath;
FileUpload.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, DocNo, true);
DocNo = DocNo + 1;
Label.Text = "Successfully added in list";
}
}
The last line of the first section(FileUpload.PostedFile.SaveAs(_filepath);) is where it gives the following error:
"System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Spapps\AppData\Local\Temp\131613662837501509~testdoc2.pdf'
is denied.' "
Is this a known issue and is there a solution that can help me out?
Try with spsecurity.runwithelevatedprivileges
I've been looking to close this question but didnt find how to so Ill state it here as an answer. I havent found a solution, but I worked around this issue in my project by altering the approach; I do not temporarily upload and display the files anymore. They are deleted from the doclib if the procedure is cancelled.
I'm having a little bit of trouble writing to a text file within a folder I tried to create. It said I didn't have access to the path 'C:\'
Could anyone tell me why and how to fix it? Thanks!
string file_name = Environment.CurrentDirectory;
file_name += #"\.";
file_name = (string)combobox1.SelectedValue;
file_name += #"\.";
file_name += (string)combobox2.SelectedValue;
TextWriter name = new StreamWriter(file_name);
EDIT: Here's the new code after revisions...
var location = Path.Combine(Environment.CurrentDirectory, (string)combobox1.SelectedItem);
Directory.CreateDirectory(location);
var path = Path.Combine(location, combobox2.SelectedItem);
TextWriter name = new StreamWriter(path, true);
My goal is to write a text file to \\.txt
Could anyone tell me how? Thanks!
have you checked the value of file_name to make sure is a valid Path?
you have missed a concatenation anyway at line number 3
string file_name = Environment.CurrentDirectory;
file_name += #"\.";
file_name += (string)combobox1.SelectedValue; // <--
file_name += #"\.";
file_name += (string)combobox2.SelectedValue;
TextWriter name = new StreamWriter(file_name);
The account that the application is running under does not have write permissions in the location you are trying to save the file to.
This article goes over how to resolve this issue:
http://www.phdcc.com/findinsite/instperm.htm
You should be using Path.Combine():
var fileName = Path.Combine(Environment.CurrentDirectory, (string)comboBox1.SelectedValue,
(string)comboBox2.SelectedValue);
If at that point it still doesn't work, at least you'll know it's actually a permissions/existence/etc. issue, rather than an issue with the way you've constructed the file name.
The solution here is a combination of what everyone else has said.
As has already been pointed out, this line:
file_name = (string)combobox1.SelectedValue;
is incorrectly doing an assignment (=) instead of a concatenation (+=). This means that if comboxbo1.SelectedValue is null, your path becomes \., which is the root directory of the drive.
You need to remember that it's legal for SelectedValue to be null, because a combo box can have an empty selection. You need to handle that case, perhaps by disabling your save functionality until the combo boxes have valid selections.
This isn't really a problem with permissions; it's unlikely that you actually need or intend to write to the root directory, which is why you aren't given that permission in the first place.
I am trying to check if a file is on the server with the C# code behind of my ASP.NET web page. I know the file does exist as I put it on the server in a piece of code before hand. Can anyone see why it is not finding the file. This is the code:
wordDocName = "~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc";
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
btnDownloadWordDoc.Visible = true;
}
else
{
btnDownloadWordDoc.Visible = false;
}
the file path should be physical not virtual. Use
if (File.Exists(Server.MapPath(wordDocName)))
File.Exists() and probably everything else you want to do with the file will need a real Path.
Your wordDocName is a relative URL.
Simply use
string fileName = Server.MapPath(wordDocName);
Use
Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc")
to get the fully-qualified path. That should do the trick for ya.
You need to use Server.MapPath e.g.
wordDocName = Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc");
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
btnDownloadWordDoc.Visible = true;
}
else
{
btnDownloadWordDoc.Visible = false;
}
this might not work if the directory holding the file is referenced by a junction/symbolic link. I have this case in my own application and if I put the REAL path to the file, File.Exists() returns true. But if I use Server.MapPath but the folder is in fact a junction to the folder, it seems to fail. Anyone experienced the same behaviour?
The character "~" is a special char in ASP.NET to get virtual path specifications and simply means "root directory of the application". Is is not understood by the .NET BCL like the File API and must be mapped first into a physical path with Server.MapPath() as others stated.
You have to convert the path to a physical path with Server.MapPath(relativePath)
if (File.Exists(filePath))
wordDocName = "~/specifications/" + ViewState["projectSelected"] + ".doc";
btnDownloadWordDoc.Visible = File.Exists(Server.MapPath(wordDocName));
string docname="traintatkalantnoy.txt";
string a = (Server.MapPath(docname));
if (File.Exists(a))