I'm working on a project where we generating folders for users, my question is that is it possible to create those folders with one particular user as admin in code behind?
if (!Directory.Exists(Server.MapPath("~/Files/" + compamyFolder + "/User/" + folder)))
{
Directory.CreateDirectory(Server.MapPath("~/Files/" + compamyFolder + "/User/" + folder));
}
Use the below code as per http://forums.asp.net/p/1226236/2209871.aspx:
string subPath ="ImagesPath"; // your code goes here
bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!isExists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
Happy coding!!
how about
string folderPath = #"C:\myRootFolder";
if(!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
Related
string UserFolder = Session["Username"].ToString();
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
filePathE = Server.MapPath("~/MisReports/EmailAttachment/" + UserFolder + "/");
filePathE = filePathE + a + ".pdf";
bool isExist = File.Exists(filePathE);
if (isExist)
{
File.Delete(filePathE);
}
report.ExportToDisk(ExportFormatType.PortableDocFormat, filePathE);
I get the error
Could not find a part of the path
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
in this area code does not enter if check although that the folder has not been created
The ~ is probably not evaluated if you are running on Windows. Windows is not Unix. Read up on Path.Combine, Environment.GetFolderPath and Environment.SpecialFolder on MSDN. You should build a path with code like
string directoryName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "MisReports/EmailAttachment", UserFolder);
public static void CreateFolder()
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); //Gets desktop folder
string pathTo = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/" + "SYS_" + Random6CharString() + "/"; //Creates random directories
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
}
public static string Random6CharString()
{
string path = Path.GetRandomFileName();
path = path.Replace(".", ""); // Remove period.
return path.Substring(0, 6); // Return 6 character string
}
I'm making a game, and it should write folders to the users desktop to use as events on the game. When I get to a point, where 2 folders should be created simultaneously, it only creates one folder. Can anyone tell me how to make more than 1 folder at once? Or at least do them one after another instead of simultaneously? Thanks guys!
string pathTo = ...
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
You're using pathTo instead of the path variable of your foreach. So you're trying to create two folders with the same name in the same location (which it doesn't by the way, CreateDirectory can't overwrite an existing folder).
Look at your code:
string pathTo = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/" + "SYS_" + Random6CharString() + "/"; //Creates random directories
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
You're creating pathTo twice.
You could easily generate a random value for the path by using System.Guid.NewGuid(), by the way.
I am moving files from source folder to destination folder. Before moving files, I am checking that directory exists or not which is working fine. The issue is with my second check where I want to make sure that folder is not empty before moving files but it is not giving me correct result.
public void MoveFilesFromTempToSourceTbl()
{
//Moving all files from temp folder to orig folder.
string sourceFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString() + "_Temp").Replace("\\", #"\");
string destinationFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString()).Replace("\\", #"\");
string pattern = "*.txt";
if (Directory.Exists(sourceFolder))
{
if (File.Exists(pattern))
{
foreach (var file in new DirectoryInfo(sourceFolder).GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
}
if (Directory.GetFiles(sourceFolder).Length == 0) //Before deleting make sure that Temp folder is empty.
Directory.Delete(sourceFolder, true); // Delete Temp folder after moving all the contents.
}
}
I know I am making some small mistake but not sure what it is. Following is the screenshot of the result which I got in immediate window.
http://imgur.com/FZvo9cj
There's a bit of redundancy in your current code. Starting with the if-checks, here's how I would approach this:
var sourceDirectory = new DirectoryInfo(sourceFolder); // remember this, it is reused
if (sourceDirectory.Exists)
{
// Look for the files in the directory, if none found, will be empty array
foreach (var file in sourceDirectory.GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
// Re-check the directory for any remaining files
if (sourceDirectory.GetFiles(pattern).Length == 0) //Before deleting make sure that Temp folder is empty.
sourceDirectory.Delete(); // Delete Temp folder after moving all the contents.
}
As a small performance improvement, you could replace sourceDirectory.GetFiles() with sourceDirectory.EnumerateFiles() in the for-loop. This will allow you to start moving them as the method finds them, not after they have all been found.
You are passing "*.txt" into the File.Exists() call when you need to be passing a path.
You can read the Documentation here
Alternatively you could use something like this:
Directory.GetFiles(destinationFolder).Contains(filename)
I agree with David here but also I think the flow of you logic should be adjusted a bit. The File.Exixts(filename); should occur inside the foreach.
That will allow you to iterate each file and if it exists do something.
Try adding the following to check if any files exist in the location:
bool exist = Directory.EnumerateFiles(sourceFolder, "*.txt").Any();
I am trying to create folders in nested manner.
if (file.ContentLength > 0 && file != null)
{
string path = "~/Videos/" + Session["username"] + "_" + Session["userid"];
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = path + file.FileName;
filepath = "/Videos/" + Session["username"] + "_" + Session["userid"];
file.SaveAs(filename);
If you see here- /Videos/ folder is what I have currently on disk. Where another folder with user's name and id is what I want to create inside this Videos folder. How Would I be creating this folder inside this folder?
Because currently it is showing me this error -
Access to the path '~/Videos/shaun_2' is denied.
I tried restarting visual studio with administrator's credentials. But it still remains here.
I'm assuming that you are using ASP.NET: try to use Server.MapPath("~/...") to get the physical path
See MSDN
I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.