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;
Related
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'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}";
I am trying to upload a file using devexpress save as function which works exact same as the standard asp.net uploader but i am getting the following error
Could not find a part of the path 'C:\Projects\fhs\fhs\Uploads\documents\VX00150\Barry Allen\Aperture - Signature Template.docx'.
UploadDirectory refers to a virutal directory setup in the web config which im getting via the property.
string UploadDirectory = WebConfigurationManager.AppSettings["uploadDirectory"].ToString();
Which contains the directory
<add key="uploadDirectory" value="~\Uploads\" />
But for the live of me I cannot see why the file is not saving to the server
protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
{
UploadControl.Enabled = false;
string id = Request.QueryString["Case"];
if (id != null)
{
CaseId = Guid.Parse(id);
OpenCase = _dal.GetCaseById(Guid.Parse(id));
}
string PersonId = Session["CurrentPersonalMainID"].ToString();
Personal = _dal.GetPersonalByPersonalId(new Guid(PersonId));
e.CallbackData = SavePostedFile(e.UploadedFile, OpenCase.CaseReference, Personal.firstName, Personal.lastName);
}
The below saved postedfile is called from above
public string SavePostedFile(UploadedFile uploadedFile,string IVACaseRef, string firstName ,string lastName)
{
try
{
if (!uploadedFile.IsValid)
return string.Empty;
string fileName = uploadedFile.FileName;
FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
string fullFileName = CombinePath(fileName);
string docsPath = UploadDirectory + #"documents\" + IVACaseRef + #"\" + firstName + " " +
lastName + #"\";
string resFileName =docsPath + fileInfo.Name;
bool exists = System.IO.Directory.Exists(resFileName);
if (!exists)
System.IO.Directory.CreateDirectory(docsPath);
uploadedFile.SaveAs(Server.MapPath(resFileName), true);
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(resFileName.ToString());
// we need to reget this as issue with postback and the fileuplaod
FormsIdentity _identity = (FormsIdentity)Context.User.Identity;
_identity = (FormsIdentity)Context.User.Identity;
return fileName;
}
catch (Exception ex)
{
string inner = string.Empty;
if (ex.InnerException != null)
{
inner = ex.InnerException.ToString();
}
// logger.Error("Error in GetNotificationById function aperturenetdal " + ex.ToString() + " " + inner);
return "";
I've noticed that a lot of file manipulation methods and classes differ in how they handle spaces, sometimes in ways that are not well documented. For example, I've seen situations where testing for the existence of a file with a space in the filename succeeds but opening it does not.
It's just a hunch, but it seems likely.
dynamic counter = 1;
string FileNameWithoutExtestion = "";
FileNameWithoutExtestion = file.Split('.')[0];
string FileExtestion = file.Split('.')[1];
while (System.IO.File.Exists(Dir + file))
{
if (true)
{
counter = counter + 1;
if (FileNameWithoutExtestion.EndsWith('_'))
{
file = FileNameWithoutExtestion + counter.ToString() + "." + FileExtestion;
}
else
{
file = FileNameWithoutExtestion + "_" + counter.ToString() + "." + FileExtestion;
}
}
}
if (FileNameWithoutExtestion.EndsWith('_')) //the error occurred here
Whats wrong ?
String.EndsWith() only has overloads with string as parameter, you insert a char.
Replace
.EndsWith('_')
with
.EndsWith("_")
and i would use those path-methods to parse filenames and extensions
string FileNameWithoutExtestion = System.IO.Path.GetFileNameWithoutExtension(file);
string FileExtestion = System.IO.Path.GetExtension(file); //.jpg
because FileNameWithoutExtestion = file.Split('.')[0]; will lead to a invalid value in case of a filename like foo.bar.jpg
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.