I am new at programming and I'm trying to add into a string variable the path to create a txt File. However I'm not getting it right if can it be done using Replace or Concat. I have never used that on C#. Here´s what I´ve done so far:
string path = #"###";
do
{
Console.Write("Insert the path in oder to export data: ");
string temp = Console.ReadLine();
}
while (String.IsNullOrEmpty(path));
path = path.Replace("###", "temp");
The following line
path = path.Replace("###", "temp");
replaces the part ### in the path with the literal string temp.
At the end of the operation, contents of your path variable will be "temp".
You don't really need to do a Replace at all. Instead,
string path = string.Empty;
do
{
Console.Write("Insert the path in oder to export data: ");
path = Console.ReadLine();
}
while (String.IsNullOrEmpty(path));
will assign the user entered path into your path variable.
Related
I've got a bit of a weird issue going on right now. I am trying to load a localization json file from StreamingAssets. I am using Path.Combine to combine StreamingAssetsPath and Path together to form the full path. The value of Path is en-us. But for some reason Path.Combine is throwing a \ when concatting the strings so my path is invalid. If I change the value of Path to /en-US then it cuts the Application.StreamingAssetsPath portion off completely.
Debug.Log result of Path = en-US:
C:/Users/bluem/Documents/Fishtale/Assets/StreamingAssets\en-US
Debug.Log result of Path = /en-US
/en-US
I just cannot make heads or tales of this weirdness lol.
public void LoadLocalizedText()
{
localizedText = new Dictionary<string, string>();
string filePath = Path.Combine(Application.streamingAssetsPath, path);
Debug.Log(filePath);
if (File.Exists(filePath))
{
string dataAsJson = File.ReadAllText(filePath);
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
}
Debug.Log("Localization Manager: Data loaded, dictionary contains: " + localizedText.Count + " entries.");
}
else
{
Debug.LogError("Localization Manager: Cannot find data file name: " + filePath);
return;
}
isReady = true;
}
I will answer my own question. The responses provided were helpful, but not the solution to the problem.
The problem is not actually in the code, but rather the reference to the file being passed. The file needs to include the extension of .json or it simply will not find it. So in this case the answer is to change the value of Path from en-US to en-US.json.
I am pretty new to C# and I am trying to get my program to copy a file from one location to another. The method I have is as below;
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceFile = "F:\\inetpub\ftproot\test.txt";
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, copyPathone);
}
As you can is there is a fixed source location however the destination is taken from user input (text box). The problem I have however, is that when I try to copy to a location for example C:\testfolder. I get an illegal character exception.
Look at your sourceFile string and be aware of using the \, which could be interpreted as escape character.
To prevent this start your string with #
string sourceFile = #"F:\inetpub\ftproot\test.txt";
or
string sourceFile = "F:\\inetpub\\ftproot\\test.txt";
File.Copy requires the full filename for the destination.
destFileName
Type: System.String
The name of the destination file. This cannot be a directory.
If your input is just the folder name then you need to add the filename of the source file.
private void CopyInstallFiles(object sender, EventArgs e)
{
// The correct syntax for a path name requires the verbatim # char
string sourceFile = #"F:\inetpub\ftproot\test.txt";
string file = Path.GetFileName(sourceFile);
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, Path.Combine(copyPathone, file), true);
}
Note the final parameter = true to overwrite a file in the destination folder.
As a side note, I suggest you to remove the textbox as input for a folder name but instead use the FolderBrowserDialog
Try this :
string path = #"C:\Program Files (x86)\your\path\main.txt";
This is because in C# (and C++ and C and some other languages) string can contain special characters. Those characters are followed by '\'. So for example string:
"\n"
Will not show you \n This is special character called - new line. So, when you create path like that:
"C:\Dir\file.txt"
C# expects that there are two special characters: \D and \f. But there is no special characters like that. Thus the error.
To put character '\' into string you have to double it, so:
"\\n"
would output \n
The same is with paths: "C:\Dir\file.txt"
C# has an alternative. You can have single '\' in path, but such a string must be followed by at sign (#):
string properPath = #"C:\dir\file.txt";
string properPath2 = "C:\\dir\\file.txt";
string error = "C:\dir\file.txt"
Either FIle.Copy
Move it to new location like below
new_file_path = file_path.Replace(".xls", " created on " + File.GetLastWriteTime(file_path).ToString("dd-MM-yyyy hh-mm-ss tt") + ".xls");
File.Move(file_path, new_file_path);
File.Delete(file_path);
I have a console application in C# and I would like to load an xml file, the path to the file is provided via console.readline(). But, I would like to load the file from the provided path but if the user only provides the name of the file I would like to search for it in the local folder from where the application is running. How can I know when I get only a file name as an input or a file full path.
I managed that using: var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
But this ugly and probably very buggy.
Full code:
var xmlFilePath = Console.ReadLine();
var xmlFile = new XmlDocument();
var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
try
{
if (isFileNameOnly)
{
xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFilePath);
}
xmlFile.Load(xmlFilePath);
}
Thx
You can check if the file name entered by user actually exists using Exists() method. If it returns true load the file.
File.Exists(xmlFilePath)
Also XmlDocument.Load() if provided only file name will try to find the file in the BaseDirectory itself. So if file.Exists() return true you can assume XmlDocument.Load will load it whether it is local or absolute path.
This will return false:
bool isFolder = Path.IsPathRooted(#"Text.txt");
This will return true:
bool isFolder = Path.IsPathRooted(#"C:\Text");
Your approach is the same that I would have chosen. If the param doesn't contain any directory delimiter char, then it must be a filename only. Maybe it would be a little more elegant if you did it like this:
bool isFileNameOnly = !xmlFilePath.Contains(Path.DirectorySeparatorChar.ToString());
Been working on file directory stuff in C# and I think i might just be forgetting something simple here. So lets says I have 4 folders and I need to check if the folder exists and then display the files within the folder. But the part that I'm stuck at is checking lets say the creationdate of a file WITH one of the four folders. Almost like I'm missing the path actual path to the file within the folder. Here the code that i had so far.
string end;
string directoryName;
string fileName;
string[] listOfFiles;
Console.Write("Enter the name of the folder: ");
directoryName = Console.ReadLine();
while (directoryName != "end")
{
if (Directory.Exists(directoryName))
{
Console.WriteLine("Directory exists, and it contains the following:");
listOfFiles = Directory.GetFiles(directoryName);
for (int x = 0; x < listOfFiles.Length; ++x)
Console.WriteLine(" {0}", listOfFiles[x]);
}
Console.Write("Enter a filename: ");
fileName = Console.ReadLine();
if(File.Exists(fileName)) // Almost like a path needs to be here.
{
Console.WriteLine("File was created " + File.GetCreationTime(fileName));
}
}
just thought incase it was asked the programs exe and folders are all located together
Your intuition is correct. File.Exists takes a full path (just like pretty much every other Filesystem API).
Add the path with Path.Combine(). See How do I join two paths in C#?
fileName = Console.ReadLine();
var filePath = Path.Combine(directoryName, fileName);
if (File.Exists(filePath)) // Almost like a path needs to be here - Yep!
I'm developing a console application that parse xml files and generate a txt file. I have created the file path to store the new file, but this is having white spaces, like this:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
but I'm creating the path using:
string filePath = Path.Combine(temp, "fileName.txt");
while temp is the previous path. And when I call:
StreamWriter sw = File.CreateText(filePath);
Is giving this exception:
Could not find a part of the path: filePath
Can someone help me with this issue?? how can I create the file with this path?
there looks like a problem with you file path
try#"C:\Program Files\my path\fileName.txt"
Note: You've updated your question with the changes mentioned in the comments.
Your issue is probably that 'my path' doesn't exist as this console application works OK for me when run as an administrator. When not run I get an UnathorizedAccessException
class Program
{
static void Main(string[] args)
{
try
{
var temp = #"C:\\Program Files\\my path\\";
string filePath = Path.Combine(temp, "fileName.txt");
StreamWriter sw = File.CreateText(filePath);
Console.WriteLine("I got here");
}
catch (Exception)
{
Console.WriteLine("I didn't");
//
}
}
}
Use this:
string filePath = #"C:\Program Files\my path\fileName.txt"
You have single backslashes in the string. Make them double backslashes:
string filePath = "C:\\Program Files\\my path\\fileName.txt"