I have to create a directory and then a text file inside this directory with name come from parameter. E.g. _year is a parameter and I tried as:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results";
var _clusterFilename = _year.ToString() + "cluster.txt";
var _path = Path.Combine(_root, _year.ToString(), _clusterFilename);
if(!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
// output topk file
TextWriter _twClus = File.CreateText(_path);
foreach (// loop )
{
_twClus.WriteLine("Cluster");
//... rest of the implementation...
}
This code is creating a folder named 2005 at specified path and then inside this folder, there is another folder named 2005cluster.txt while I want to create a text file named 2005cluster.txt inside folder 2005.
Where I am getting wrong in creating correct folder and file names?
An UnauthorizedAccessException generated at undermentioned line of
code i.e. access is denied. Why is this happening?
TextWriter _twClus = File.CreateText(_path);
Try this so that your path has a slash before the file name:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results\\";
As you are defining fileName separately, You could try this:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results";
var _clusterFilename = _year.ToString() + "cluster.txt";
var _path = Path.Combine(_root, _year.ToString());
if(!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
// output topk file
TextWriter _twClus = File.CreateText(Path.Combine(_path, _clusterFilename));
foreach (// loop )
{
_twClus.WriteLine("Cluster");
//... rest of the implementation...
}
Remove the file name from your path as:
var _path = Path.Combine(_root, _year.ToString());
For defining the filename you have to modify this line of code as:
TextWriter _twClus = File.CreateText(Path.Combine(_path, _clusterFilename));
Related
The code below creates XML file next to executable file of App.
However, I would like to have an XML file created in a certain folder next to the executable file.
For example (I want to get behaviour like this):
// same directory
App.exe
ParametersFolder (here lies Parameters.xml)
// same directory
The code I'm currently using
public static void Save()
{
using (var file = File.Create(Singletone.FileName))
formatter.Serialize(file, Singletone);
}
and deserialization
public static void Load()
{
try
{
Parameters parameters;
using (var file = File.OpenRead(Singletone.FileName))
parameters = (Parameters)formatter.Deserialize(file);
Singletone.Text1 = parameters.Text1;
Singletone.Text2 = parameters.Text2;
}
catch (Exception)
{
Singletone.Text1 = "first";
Singletone.Text2 = "second";
}
}
Adding a folder to the file can be simply done by combining Path.GetDirectoryName, Path.GetFileName and Path.Combine:
string oldPath = Singletone.FileName;
string folderToAdd = "ParametersFolder";
string newPath = Path.Combine(Path.GetDirectoryName(oldPath),
folderToAdd,
Path.GetFileName(oldPath));
I'm Currently inside a for loop which iterates through a set of folders and obtains some required values from a JSON file. I also want to get the absolute path to each of those files.
Currently I tried approaches such as
string currentDir = AppDomain.CurrentDomain.BaseDirectory; string
currentDir = Directory.GetCurrentDirectory();
Both of these gave me location to the debug file
what I want is the location of the Folder in which this file is existing rather .
Below is the code segment to which I hope to include this new code.
string rootDirectory = fbd.SelectedPath;
var foundFiles = Directory.EnumerateFiles(rootDirectory,
"server.config", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{ RepositoryHomeSettingsModel repositoryHomeSettingsModel =
JsonConvert.DeserializeObject(File.ReadAllText(file));
string Name = SettingsModel.name;
}
Please find below possible ans,Do you require the same ?
var foundFiles = Directory.EnumerateFiles(rootDirectory, "*.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{
var folderpath= Path.GetDirectoryName(file);
//RepositoryHomeSettingsModel repositoryHomeSettingsModel = JsonConvert.DeserializeObject(File.ReadAllText(file));
//string Name = SettingsModel.name;
}
I am trying to construct a file path in order to read an XSLT file, like so:
string path = "../_xslt/example.xslt";
StreamReader reader = new StreamReader(path);
...where I am in a controller (/Controllers/ExampleController.cs), and the '/_xslt/' folder is at the same level as '/Controllers'
However, the error I am getting is:
(System.IO.DirectoryNotFoundException)
Could not find a part of the path 'c:\windows\system32\_xslt\example.xslt'.
Am I going about this the wrong way?
Thanks for any help!
You can use the HttpServerUtility.MapPath method to map any relative paths for you, in your controller this is easily accessible via the ControllerContext:
string path = ControllerContext.HttpContext.Server.MapPath("~/_xslt/example.xslt");
...
string TestX()
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You get main rott
string dirc = ""; // just var for use
string[] pathes = Directory.GetDirectories(path); // get collection
foreach (string str in pathes)
{
if (str.Contains("NameYRDirectory")) // paste yr directory
{
dirc = str;
}
}
return dirc; // after use Method and modify as you like
}
If controller is present at directory root
String path = ControllerContext.HttpContext.Server.MapPath(#"~/_xslt/example.xslt");
Else
String path = ControllerContext.HttpContext.Server.MapPath(#"../_xslt/example.xslt");
I'm using a code to show all startup items in listbox with environment variable "%appdata%
There is some errors in this code that I need help with....
Check code for commented errors
Is there any other solution but still using %appdata%?
This is the code:
private void readfiles()
{
String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
foldertoread(startfolder);
}
private void foldertoread(string folderName)
{
FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
foreach (var file in Directory.GetFiles(folderName))
{
startupinfo.Items.Add(file.Name); // here is another error "Name"
}
}
This line won't work because folderName is a string (and does not have a GetFiles method):
FileInfo[] Files = folderName.GetFiles("*.txt");
The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:
startupinfo.Items.Add(file);
I don't think you need the following line:
FileInfo[] Files = folderName.GetFiles("*.txt");
The foreach loop will generate what you need.
Secondly, the file variable is a string, so rather than calling:
startupinfo.Items.Add(file.Name);
...call instead:
startupinfo.Items.Add(file);
Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:
foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
The string object doesn't have a GetFiles() method. Try this:
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string[] files = Directory.GetFiles(startfolder, "*.txt");
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}
Path.GetFileNameWithoutExtension(file) returns just the file name instead of full path.
I want to read the first line of a text file that I added to the root directory of my project. Meaning, my solution explorer is showing the .txt file along side my .cs files in my project.
So, I tried to do:
TextReader tr = new StreamReader(#"myfile.txt");
string myText = tr.ReadLine();
But this doesn't work since it's referring to the Bin Folder and my file isn't in there... How can I make this work? :/
Thanks
From Solution Explorer, right click on myfile.txt and choose "Properties"
From there, set the Build Action to content
and Copy to Output Directory to either Copy always or Copy if newer
You can use the following to get the root directory of a website project:
String FilePath;
FilePath = Server.MapPath("/MyWebSite");
Or you can get the base directory like so:
AppDomain.CurrentDomain.BaseDirectory
Add a Resource File to your project (Right Click Project->Properties->Resources). Where it says "strings", you can switch to be "files". Choose "Add Resource" and select your file.
You can now reference your file through the Properties.Resources collection.
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
The method above will bring you something like this:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
From here you can navigate backwards using System.IO.Directory.GetParent:
_filePath = Directory.GetParent(_filePath).FullName;
1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:
_filePath += #"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
Hope it helps.
You can have it embedded (build action set to Resource) as well, this is how to retrieve it from there:
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
string resName = "Test.txt";
var file = GetResourceStream(resName);
using (var reader = new StreamReader(file))
{
var line = reader.ReadLine();
MessageBox.Show(line);
}
}
(Some code taken from this answer by Charles)
You have to use absolute path in this case. But if you set the CopyToOutputDirectory = CopyAlways, it will work as you are doing it.
In this code you access to root directory project:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
then:
StreamReader r = new StreamReader(_filePath + "/cities2.json"))