What is wrong with this code? The text file is not created in the bin\Debug directory!
string path = Environment.CurrentDirectory + "/" + "Contacts.txt";
if (!File.Exists(path))
{
File.CreateText(path);
MessageBox.Show("file created successfully");
}
using (StreamWriter sw = new StreamWriter("path", true))
{
sw.WriteLine(txtCntname1.Text + "," + txtCntnum1.Text + "," + txtCntnum2.Text + "," + txtCntnum3.Text + ",");
sw.Close();
}
You have two ways of calculating EXE's directory:
1) Implicit
You can use only the file name. In this case, the file will be created in the same folder with EXE file:
File.CreateText("Contacts.txt")
2) Explicit
If you need reliable way to get the EXE's directory, then you need to use AppDomain:
string exe_dir = AppDomain.CurrentDomain.BaseDirectory;
Then, instead of manually concatenating strings to form a path, use Path.Combine method:
string file_path = Path.Combine(exe_dir, "Contact.txt");
The code (Assembly.GetExecutingAssembly().Location), offered by #TobiasTengler, won't work, for instance, for Excel/Word add-in.
Aside from that path should probably not be in quotes here:
using (StreamWriter sw = new StreamWriter("path", true))
Do not use Environment.CurrentDirectory! It does not always represent the directory you started your executable from, since it only represents your working directory.
Please use Assembly.GetExecutingAssembly().Location to get the full path of the executing assembly and then extract only the directory from it, using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Alternatively you could also use AppDomain.CurrentDomain.BaseDirectory for identifying the directory your application is residing in.
Of course not using an absolute path is a possibility as well, you can create your file using a relative path, by not specifying any directory:
File.CreateText("Contacts.txt")
EDIT:
Seeing how you formed your path, please also use Path.Combine to build your paths:
var appBaseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var contactsFilePath = Path.Combine(appBaseDir, "Contacts.txt");
Related
Consider the following code:
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string file = Path.Combine(folder, "test.txt");
File.WriteAllText(file, "test");
string content = File.ReadAllText(file);
Running this on my phone I confirmed that the string content has the value "test", so the file has definitely been created and written to in internal storage.
Next I commented the WriteAllText-line and verified on a second run of the program that the file was still there because the value of content again was "test".
But when I look into the folder returned by GetFolderPath using the file manager of my phone, it is empty. There is no file test.txt.
So the question is, why can't I see the file?
Unless the phone is rooted and the file manager as root permissions you cannot see those files (usually under /data/data/package.name/files)
If you want to see them using your code, consider using this:
String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
Your app should log them with no problem.
If the files are needed outside the app, consider using external storage.
I want to download a folder with its files in various mime type. My virtual path is "http://localhost/attachments/". My sub folders are "certificates/id". So when clicking on a grid i pass id to the download page. But it throws an exception like virtual path is invalid. 'http://localhost/attachments/certificates/id)'.
In below code, Request.Params[0] meant id, this points the endlevel folder which i want to make a zip folder.
Any guidance would be grateful.
using (ZipFile zip = new ZipFile())
{
string VirtualPath = ConfigurationManager.AppSettings.Get("AttachmentsShowVirtualPath");
string Path = string.Empty;
Path = "certificates" + "/";
string folderPath = VirtualPath + Path + Request.Params[0] + "/";
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles(".", Server.MapPath(folderPath), "", false);
zip.Save(Response.OutputStream);
}
First, are you using DotNetZip? I have never use it, but try changing the . to *.*
If not getting the file, try to do Directory.GetFiles to check if eveything is pointing correctly and your code has read permission over the directory https://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx
Or try to use official Zip class from https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx With this method: ZipFile.CreateFromDirectory
i wrote this code , it ctreates folder named "Fitness50" each time but the text file is not created.i want to create textfile within this folder and then save values of an arraylist.
so for i have tried this
DirectoryInfo myDir = new DirectoryInfo(#"E:");
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
myDir = new DirectoryInfo(ParentFolderName1);
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
FileName1 = "./" + "" + ParentFolderName1 + "" + "/" + "Fittness10" + "" + "" + PopulationID + "" + ".txt";
FileStream fs2 = new FileStream(FileName1, FileMode.Create, FileAccess.Write);
StreamWriter SW2 = new StreamWriter(fs2);
for (i = 0; i < AlTargetData.Count; i++)
{
SW2.WriteLine(AlTargetData[i]);
}
AlTargetData.Clear();
SW2.Close();
fs2.Close();
Well, first of all, / is not the preferred directory separator on Windows, but \ is. Just because / happens to work, there's no reason to use it. Secondly, you're not creating the Fittness10 folder at all, but you're creating Fittness50 twice. And third, you're not writing the file to the folders you create, but to the current working directory ..
Your code (or at least what I understand you want to achieve) can be shortened significantly to this:
string path = #"E:\Fittness50\Fittness10";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = Path.Combine(path, String.Format("{0}.txt", PopulationID));
File.WriteAllText(fileName, String.Join(Environment.NewLine, AlTargetData));
Please note that you should not consider writing to bin\debug. There will be no bin\debug on the end-user's machine. If the user installs your application, it will be most probably be installed in the Program Files folder, which your application won't be allowed to write to. Instead, consider writing to a common location, like the ones you can chose from in Environment.GetFolderPath.
The end-user supplies a path, indicating where the original document is.
string DocxFileName = "C:\\WorksArshad\\3.docx";
I'd like to create a copy of the document name 3.docx as 3Version1.docx and store the copy in the same directory as the original.
How do I get the whole path without the file name and extension?
(i.e.) I need to get the "C:\\WorksArshad\\" path alone.
FileInfo file = new FileInfo(Session.FileName);
string path = file.Directory.tostring();
and then using
string fileName = Path.GetFileNameWithoutExtension(Session.FileName);
string DocxFileNamee = path + "\\" + fileName + "V1.docx";
File.Copy(Session.FileName, DocxFileNamee, true);
where in Session.FileName = "C:\WorksArshad\3.docx" and in path I'd get "C:\WorksArshad"
requirement solved .
Or
File.Copy(Session.FileName, Path.Combine(Path.GetDirectoryName(Session.FileName)
, Path.GetFileNameWithoutExtension(Session.FileName)+"V1.docx"),true);
both the above gives the solution
I am trying to use xmltextwriter and assign a path which needs to use for writing.
I am trying this:
string path = "~/Uploads/site/" + Current.User.Id + .kml";
XmlTextWriter xtr = new XmlTextWriter(path, System.Text.Encoding.UTF8);
I want the file to be saved in the uploads/site/ folder within the website directory, but I am getting an error:
Could not find a part of the path 'c:\windows\system32\inetsrv\~\Uploads\site\16.kml'.
I would like to know how I can assign the desired path to the xmltextwriter.
Thanks in advance, Laziale
Use server.MapPath method to get the right path.
string path = Server.MapPath("~/Uploads/site/" + Current.User.Id + ".kml");
Heres an error
string path = "~/Uploads/site/" + Current.User.Id + .kml";
should be
string path = "~/Uploads/site/" + Current.User.Id + ".kml";
Still it wont work, and the answer is illustrated in this question Map the physical file path in asp.net mvc
You get this error because you need to use Server.MapPath
Otherwise the code is trying to map on your pc and not the server
string path = Server.MapPath("~/Uploads/site/" + Current.User.Id + ".kml");