I'm trying to build a directory path by injecting a userID and portalID where needed.
string userID = HttpContext.Current.Request.Params["userID"];
string portalID = HttpContext.Current.Request.Params["portalID"];
// This is the acutal path ---> string folderName = #"C:\DotNetNuke 8.0\Portals\0\Users\017\17\17";
string folderName = "c:\\DotNetNuke 8.0\\Portals\\" + portalID + "\\Users\\0" + userID + "\\" + userID + "\\" + userID;
HttpContext.Current.Response.Write(folderName);
// This is what's returned ---> c:\DotNetNuke 8.0\Portals\\Users\0\\
best approach would be to use Path.Combine method, like this:
string userID = "testuser";
string portalID = "portal";
var path = Path.Combine(#"c:\DotNetNuke 8.0\Portals", portalID, "Users", "0" + userID, userID, userID);
Console.WriteLine(path);
Result will be
c:\DotNetNuke 8.0\Portals\portal\Users\0testuser\testuser\testuser
To find more about Path.Combine check MSDN documentation.
What you have is actually correct. It looks like portalID and userId are null or an empty string "". There are easier ways to escape, though - if you use #"some \ string", then the only thing you need to escape is " to "".
Examples:
string userID = "17";
string portalID = "0";
string folderName = "c:\\DotNetNuke 8.0\\Portals\\" + portalID + "\\Users\\0" + userID + "\\" + userID + "\\" + userID;
gives
c:\DotNetNuke 8.0\Portals\0\Users\017\17\17
as does:
string folderName = #"c:\DotNetNuke 8.0\Portals\" + portalID + #"\Users\0" + userID + #"\" + userID + #"\" + userID;
as does:
string folderName = $#"c:\DotNetNuke 8.0\Portals\{portalID}\Users\0{userID}\{userID}\{userID}";
Related
I'm trying to use the Dropbox API in order to do a file upload.
string accesstoken = "token";
using (DropboxClient client =
new DropboxClient(accesstoken, new DropboxClientConfig("NameOfApp")))
{
string[] spitInputFileName = file.FileName.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
string filenameAndExtension = spitInputFileName[spitInputFileName.Length - 1];
string[] filenameAndExtensionSplit = filenameAndExtension.Split('.');
string originalFileName = filenameAndExtensionSplit[0];
string originalExtension = filenameAndExtensionSplit[1];
String filename = "" + originalFileName + Guid.NewGuid().ToString().Replace("-", "") + "." + originalExtension;
var updated = client.Files.UploadAsync(
filename,
mode: WriteMode.Overwrite.Overwrite.Instance,
body: file.InputStream).Result;
var result = client.Sharing.CreateSharedLinkWithSettingsAsync(filename).Result;
Within the body: file.InputStream.Result; section, It encounters below error :
An exception of type 'System.ArgumentOutOfRangeException' occurred in Dropbox.Api.dll but was not handled in user code
Value should match pattern '\A(?:(/(.|[\r\n])*)|(ns:[0-9]+(/.*)?)|(id:.*))\z'
What is the reason of this exception?
Paths should start with '/'.
File path should be something like this:
/test.txt
In your case:
String filename = "/" + originalFileName + Guid.NewGuid().ToString().Replace("-", "") + "." + originalExtension;
I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.
I am currently working on a project that sweeps a mailbox for attachments and when one is found it is placed in the user's directory. My problem is that when I check if the file exist in the path, I alter the attachment's name and add a counter and time stamp, that way it is not over written. However, when it goes into the condition and changes the file name it never updates the path variable to include the right value of the Clean name variable.
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
string path = employeeStarPath + "\\" + cleanName;
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
Now I am aware I can update the path var by calling path = employeeStarPath + "\\" + cleanName; again but I feel that this makes my code a bit confusing.
I might not understood your question but can you just call the line "string path = employeeStarPath + "\" + cleanName;" at the end instead before the if?
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
string path = employeeStarPath + "\\" + cleanName;
I need to update the Expiry Date and update the Cardholder Name on an existing card in Realex payments.
The hash value syntax should be in the following format:
Timestamp.merchantID.payerref.ref.expirydate.cardnumber
And here is an example of how it should look
20030516175919.yourmerchantid.mypayer.card01.1015.
When I run the following method I get the error:
"sha1hash incorrect - check your code and the Developers Documentation"
private string ReturnHash(string timeStamp, string merchantId, string payerRef, string reference, string expDate, string cardNum )
{
SHA1 hash = new SHA1Managed();
StringBuilder builder = new StringBuilder();
builder.Append(timeStamp).Append(".");
builder.Append(merchantId).Append(".");
builder.Append(payerRef).Append(".");
builder.Append(reference).Append(".");
builder.Append(expDate).Append(".");
builder.Append(cardNum );
string resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())));
resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(resultingHash)));
return resultingHash;
}
What am I doing wrong?
Thank you for your message.
Could you try before running this line of code:
string resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())));
To make "resultingHash" all lowercase?
Also before running:
resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(resultingHash)));
make "resultingHash" to lowercase as well.
Thanks,
Borja
var timeStamp = RealexDateFormatter.DateFormatForRealex();
var orderid = model.ORDER_ID;
var secret = ConfigurationManager.AppSettings["Appsecretkey"];
var merchantId = ConfigurationManager.AppSettings["AppMerchantId"];
var temp1 = FormsAuthentication.HashPasswordForStoringInConfigFile(
timeStamp + "." +
merchantId + "." +
orderid + "." +
model.AMOUNT + "." + "EUR", "sha1");
temp1 = temp1.ToLower();
var temp2 = temp1 + "." + secret;
var sha1hash = FormsAuthentication.HashPasswordForStoringInConfigFile(temp2, "sha1");
sha1hash = sha1hash.ToLower();`enter code here`
var url = "https://hpp.sandbox.realexpayments.com/pay?MERCHANT_ID="
+ ConfigurationManager.AppSettings["AppMerchantId"] +
"&ORDER_ID=" + orderid + "&CURRENCY=EUR" + "&AMOUNT=" + model.AMOUNT + "&TIMESTAMP=" + timeStamp + "&SHA1HASH=" + sha1hash + "&MERCHANT_RESPONSE_URL=http://deposit.projectstatus.in/Payment/Response";
I need to remove a pattern from a string, I think regex could do the job, but I'm having trouble solving this.
The pattern must be in the end of the string.
string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"
Edit:
Ok, here is the code that I'm using now after your answers:
public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
{
string dir = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
if (ext.Length > 0 && ext[0] != '.')
ext = "." + ext;
string baseName = Regex.Replace(fileNameNoExt, #"\s\(\d+\)", "");
string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
string path = Path.Combine(dir, fileName);
while (File.Exists(path))
{
id++;
fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
path = Path.Combine(dir, fileName);
}
return path;
}
It works, but:
It always start to count from id, I think it may be better to start
from the file name number.
I was hopping to use something like "(0)" as a method parameter that would indicate the pattern to be removed and also the "(" would be parametrized. I'm doing it "manually" now on this line: string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
You can do that without REGEX like:
string newFileName = new String(fileName
.Where(r => !char.IsDigit(r)
&& r != '('
&& r != ')'
&& r != ' ').ToArray());
This would give you File.jpg
If you only want to get the file name then you can use:
string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`
Using regex:
var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,#"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);
And thanks for #habib, I'd not have come with Path.GetFileNameWithoutExtension in this for stripping the extension.
You could use:
\s\(\d+\)\.jpg
assuming you do actually want the extension removed and the extension is always ".jpg". Otherwise:
\s\(\d+\)
Looks for a set of digits in brackets proceeded by a space.