Using custom domain name getting current path name - c#

It should not return the URL like http://something.azurewebsites.net/signup instead custom domain name space.
with JavaScript and C# as well.
able to see using developer options of the browser or using fiddler.
something like
HttpContext.Current.Request.Url.Scheme+"://"+HttpContext.Current.Request.Url.Host+"/SignUp/"

Using custom domain name getting current path name.
System.IO.Path.GetFullPath method to get the full path of the current executing assembly.
System.Reflection.Assembly.GetExecutingAssembly().Location -To get the location of the current executing assembly.
And combining the custom domain and the current path to get the complete path.
To fetch the path name for the domain space names with JavaScript you can use
window.location.hostname
'window.location.hostname` if you dont want the `port` (like `http://localhost:8080/`, `window.location.host = 'localhost:8080'` and `window.location.hostname = 'localhost`
string str = HttpContext.Current.Request.Url.PathAndQuery;
string strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(str, "/");
string customDomain = "https://www.something.com/";
string currentPath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string combinedPath = customDomain + currentPath;
Console.WriteLine("The combined pah is: " + combinedPath);
Reference taken from
MDN Web Docs

Related

How can I create a folder in the app folder in the user's AppData folder e.g. C:\User\AppData?

I've tried this:
var systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var complete = Path.Combine(systemPath, extractfilename);
But it results in:
C:\ProgramData\Extract.txt
My expected output is:
C:\User\AppData\Extract.txt
You need to create file in Environment.SpecialFolder.ApplicationData folder.
There is another way also to get its value, so you can use it also and append the path.
e.g.
string path;
path = #"%AppData%\test";
Environment.ExpandEnvironmentVariables(path);
C:\User\AppData\Local
Use Environment.SpecialFolder.LocalApplicationData:
The directory that serves as a common repository for application-specific data that is used by the current, non-roaming user.
C:\User\AppData\Roaming
Use Environment.SpecialFolder.ApplicationData:
The directory that serves as a common repository for application-specific data for the current roaming user. A roaming user works on more than one computer on a network. A roaming user's profile is kept on a server on the network and is loaded onto a system when the user logs on.
This will create a folder named "MyName" in "%appdata%".
string directoryName = "MyName";
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string mainPath = Path.Combine(appDataPath, directoryName);
Directory.CreateDirectory(mainPath);
This will create a file in "%appdata%" called "MyFile.txt" which says "Hello World".
string text = "Hello Word";
string fileName = "MyFile.txt";
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string mainPath = Path.Combine(appDataPath, fileName);
File.WriteAllText(mainPath, text);

How to convert a local file path in PC to a Network Relative or UNC path?

String machineName = System.Environment.MachineName;
String filePath = #"E:\folder1\folder2\file1";
int a = filePath.IndexOf(System.IO.Path.DirectorySeparatorChar);
filePath = filePath.Substring(filePath.IndexOf(System.IO.Path.DirectorySeparatorChar) +1);
String networdPath = System.IO.Path.Combine(string.Concat(System.IO.Path.DirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar), machineName, filePath);
Console.WriteLine(networdPath);
I wrote the above code using String.Concat and Path.Combine to get network path. But it is just a workaround and not a concrete solution and may fail.
Is there a concrete solution for getting a network path?
You are assuming that your E:\folder1 local path is shared as \\mypc\folder1, which in general is not true, so I doubt a general method that does what you want to do exists.
You are on the right path in implementing what you are trying to achieve. You can get more help from System.IO.Path; see Path.GetPathRoot on MSDN for returned values according to different kind of path in input
string GetNetworkPath(string path)
{
string root = Path.GetPathRoot(path);
// validate input, in your case you are expecting a path starting with a root of type "E:\"
// see Path.GetPathRoot on MSDN for returned values
if (string.IsNullOrWhiteSpace(root) || !root.Contains(":"))
{
// handle invalid input the way you prefer
// I would throw!
throw new ApplicationException("be gentle, pass to this function the expected kind of path!");
}
path = path.Remove(0, root.Length);
return Path.Combine(#"\\myPc", path);
}

C# Targeting a directory of which a mapname is partially known

I am trying to send a file using the smtp from gmail, but I have stumbled upon a problem.
The file will be stored in the windows appdata folder.
To add the file to the e-mail, I'm using:
attachment = new System.Net.Mail.Attachment((Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Folder1/Folder2/Folder3/result.txt"));
The code as above works, BUT:
The issue I currently have, is that Folder2 as seen above, will be a random name containing numbers, letters, and the word TEMP.
For example a12TEMP34b
I have tried and searched if I'm able to use * somehow, but can't seem to get it working.
Any ideas?
You can use Directory.EnumerateDirectories to search for a specific folder :
var folder1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Folder1");
var folder2 = Directory.EnumerateDirectories(folder1, "*TEMP*").Single();
var path = Path.Combine(folder2, "Folder3/result.txt");
attachment = new System.Net.Mail.Attachment(path)
You could parse Directory.GetDirectory into a string array and grab the first element of that array if you're sure it will always be that path.
So:
string staticPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Folder1/";
string dynamicFolder = Directory.GetDirectory(staticPath, "*TEMP*")[0];
string finalPath = dynamicFolder + "/Folder3/result.txt"

Add date stamp on uploaded file

I'm currently developing a website using asp and c#. One of the pages allows registered users to upload files. These files get stored according to the user who is logged in. A directory is created when they hit upload with there login name and id.
string userDirectory = "\\Test\\Files\\ " + User.Identity.Name + " " + User.Identity.GetUserId();
if (!Directory.Exists(userDirectory))
{
Directory.CreateDirectory(userDirectory);
}
The directory gets created without an issue and file also gets uploaded. However the problem I am now facing is I'm trying to add a date stamp to a file if it already exist in the directory so I don't overwrite it. See the code below
string fileName = Path.Combine(userDirectory, FileUpload1.FileName);
if (!File.Exists(fileName))
{
FileUpload1.SaveAs(fileName);
}
else
{
fileName = string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("_yyyy_MM_dd_HH:mm:ss"),
Path.GetExtension(fileName)
);
FileUpload1.SaveAs(fileName);
}
This keeps giving me an error:
System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path 'Test.docx' is not rooted
Does anyone know where I'm going wrong? Thanks in advance
You have to append the directory name to the path, since you stripped it off (by using GetFileNameWithoutExtension):
string newFileName =
Path.Combine( Path.GetDirectoryName(fileName)
, string.Concat( Path.GetFileNameWithoutExtension(fileName)
, DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss")
, Path.GetExtension(fileName)
)
);
Also note that using : in a file name is not supported, so I replace it with _.

Get folder on in same directory as App domain path

I have an asp.net web app and i need to get the string path of a folder in the same directory as my web app.
Currently im using this code to get the add domain path.
string appPath = HttpRuntime.AppDomainAppPath;
Which returns "c:/path/webapp", i need "c:/path/folder".
Thanks.
If you'd like a more generic approach that doesn't require knowing the starting folder:
//NOTE: using System.IO;
String startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);
Int32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);
String newPath = Path.Combine(startPath.Substring(0, pos), "folder"); //replace "folder" if it's really something else, of course
This way, whatever directory your web app is running from, you can get it, reduce it by one level, and tack on "folder" to get your new sibling directory.
You can use String.Replace method.
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
string appPath = HttpRuntime.AppDomainAppPath;
appPath = appPath.Replace("webapp", "folder");
Here is a DEMO.
Thanks to DonBoitnott comments, here is the right answer;
string appPath = #"C:\mydir\anotherdir\webapp\thirddir\webapp";
int LastIndex = appPath.LastIndexOf("webapp", StringComparison.InvariantCulture);
string RealappPath = Path.Combine(appPath.Substring(0, LastIndex), "folder");
Console.WriteLine(RealappPath);
This will print;
C:\mydir\anotherdir\webapp\thirddir\folder

Categories