Folder path. Here's my current codes:
private void button2_Click(object sender, EventArgs e)
{
String Username = Nametxt.Text;
var directoryInfo = Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E"));
directoryInfo.CreateSubdirectory(Username); // Create a Sub-Folder inside "F.U.T.U.R.E"
StreamWriter stream = new StreamWriter(Username + ".txt");
stream.WriteLine(passwordtxt.Text);
stream.Close();
}
From the current codes the text is being created in the software directory#.
Part 1:
On button click the software should create a folder entitle "F.U.T.U.R.E" then create a Sub-Folder with the NameString Username= textbox1.text.
Part2:
Creating a new StreamWriterinside the new Sub-Folder Username
Pass the full path of the file in the constructor of the StreamWriter:
String Username = Nametxt.Text;
DirectoryInfo directoryInfo = Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E")).CreateSubdirectory(Username);
StreamWriter stream = new StreamWriter(Path.Combine(directoryInfo.FullName, Username + ".txt"));
You will need to pass the full path, such as
StreamWriter stream = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E", Username) + Username + ".txt")
Related
I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.
I am trying to upload a file using File Upload. Then compare this file with a repository using IEnumerable. I want the IEnumerable list to save the path of the uploaded file. I am trying to do so, but it's giving me an error :
Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Uploaded file.txt'
The code is as follows:
//File upload method uploads the file
protected string File_Upload()
{
string strFilename;
strFilename = File1.PostedFile.FileName;
strFilename = System.IO.Path.GetFileName(strFilename);
File1.PostedFile.SaveAs(#"E:\" + strFilename); /*saves the uploaded file in the specified directory */
return strFilename; /*returns the file name and it's path*/
}
protected void Button2_Click(object sender, EventArgs e)
{
String StrFileNmae =File_Upload(); /* Receives the file name and path*/
string file1 = StrFileNmae;
IEnumerable<string> list1 = File.ReadLines(file1);
IEnumerable<string> list2 = Directory.EnumerateFiles(#"E:\DocxDB", "*.txt", SearchOption.AllDirectories);
IList<string> difference = list2.Except(list1).ToList();
if (difference != null)
{
lbl_Result.Text = "Files do not match.";
}
}
Try this, the File_Upload method returns the file name but not the path it's in. Without a path the server will try and load it from the current directory.
protected string File_Upload()
{
string strFilename;
strFilename = File1.PostedFile.FileName;
strFilename = System.IO.Path.GetFileName(strFilename);
File1.PostedFile.SaveAs(#"E:\" + strFilename); /*saves the uploaded file in the specified directory */
return #"E:\" + strFilename; // <--- Change is here
}
I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));
Thanks to you all for the help so far! I am extremely new to c# and code in general. I have a question that I cannot seem to find the answer to.
I just wrote a simple program that moves files from one folder to a new folder named that day's date. Please see below:
private void button1_Click(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
string date = (now.ToString("D"));
string a = #"m:\\staff docs\\faxes\\";
string b = #a + date + "\\";
System.IO.Directory.CreateDirectory(b);
DirectoryInfo dir1 = new DirectoryInfo("c:\\blah");
DirectoryInfo dir2 = new DirectoryInfo("#b");
FileInfo[] DispatchFiles = dir1.GetFiles();
if (DispatchFiles.Length > 0)
{
foreach (FileInfo aFile in DispatchFiles)
{
string files = #b + aFile.Name;
int count = 0;
Find :
if (File.Exists(files))
{
files = files + "(" + count.ToString() + ").txt";
count++;
goto Find;
}
aFile.MoveTo(files);
}
}
{
MessageBox.Show("Your files have been moved!");
I'd like to have the user define the source folder variable and the destination folder variable, either by having them navigate to the folder in a file browser, or a Console.ReadLine - but not every time they run the program, just the first. It would be ideal if they could change the path if they wanted to later on as well.
Many thanks!
EDIT
My solution was a Button on my Form that calls this block:
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Select source folder";
fbd.ShowDialog();
string Source = fbd.SelectedPath;
Properties.Settings.Default.source = Source;
Properties.Settings.Default.Save();
FolderBrowserDialog fbd2 = new FolderBrowserDialog();
fbd2.Description = "Select destination folder";
fbd2.ShowDialog();
string d1 = fbd2.SelectedPath;
string d2 = "\\";
string Destination = d1 + d2;
Properties.Settings.Default.destination = Destination;
Properties.Settings.Default.Save();
}
you can use the "user settings" described here: http://msdn.microsoft.com/en-us/library/bb397750.aspx
//EDIT:
let's say You have a USER Setting of type string called "MySetting"
if you want to read it:
var someVar = Properties.Settings.Default.MySetting;
if you want to write it (assuming your data is in someVar):
Properties.Settings.Default.MySetting = someVar;
Properties.Settings.Default.Save();
the call to Save() persists your changes ... the changes are bound to the windows user account
at design time your setting should be defined as Scope USER
There are a few possibilities you can use.
One thing would be to create an XML-file the first time the user entered the paths. You could check for the existance of the file and if it exists, read from it and if not exists, create it and write data to it. Of course you are capable of editing your XML-file.
There is the System.Xml.XmlDocument-class
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
string inputpath = "C:\....";
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
//Create a new node and add it to the document.
//The text node is the content of the price element.
XmlElement elem = doc.CreateElement("Inputpath");
XmlText text = doc.CreateTextNode(inputpath);
doc.DocumentElement.AppendChild(elem);
doc.DocumentElement.LastChild.AppendChild(text);
doc.Save(Console.Out);
}
}
See here for a reference.
You could write a value into the registry, too. Just as a possibility.
I am try to get my path from SaveFileDialog without my file name in order to create a DirectoryInfo object
private void btnBrowseCapture_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialogBrowse2 = new SaveFileDialog();
saveFileDialogBrowse2.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse2.Title = "Save an pcap File";
saveFileDialogBrowse2.ShowDialog();
if (saveFileDialogBrowse2.FileName != "")
{
string str = saveFileDialogBrowse2.FileName;
}
}
You can also use System.IO.Path.GetDirectoryName for this purpose
System.IO.Path.GetDirectoryName(filePath)
Use System.IO.FileInfo.DirectoryName property to get the full path of the directory of a file.
string fileName = #"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine(fileInfo.DirectoryName); // Output: "C:\TMP"
Using your example:
string str = saveFileDialogBrowse2.FileName;
FileInfo fileInfo = new FileInfo(str);
Console.WriteLine(fileInfo.DirectoryName);
string fileName = #"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine(fileInfo.DirectoryName);
You can use System.IO.Path.GetDirectoryName method:
Console.WriteLine(System.IO.Path.GetDirectoryName(Filename));