I have form with dynamic file upload:
var ordinaryPropertyValue = new Catalog.Core.Entities.OrdinaryPropertyValue();
var fileFile = Request.Files["File" + prop.Id];
if (fileFile == null) continue;
string pathFile = Server.MapPath("~/temp");
string filenameFile = Path.GetFileName(fileFile.FileName);
if (!string.IsNullOrEmpty(filenameFile)) {
fileFile.SaveAs(Path.Combine(pathFile, filenameFile));
ordinaryPropertyValue.Value = Path.Combine(pathFile, filenameFile);
instance.SetPropertyValue(prop.Id, ordinaryPropertyValue);
}
How can I rename files which are submiited from users?
just set file name you want in this line
String filenameFile = "MyFile.ext";
String pathFile = Server.MapPath("~/temp/" + filenameFile);
fileFile.SaveAs(pathFile);
this will save your file in path ~/temp/MyFile.ext
Related
I want to display list of all files(.jpg,.mp3,.psd,.tiff etc) from local storage(hard disk space) and the path of local storage gets generated when SQL query gets fired for eg. I have fields folder_name, Subfolder_name and Id.
So suppose Query: Select Folder_name,Subfolder_name From Table where Id = 101;
suppose I get output Folder_name=Users,Subfolder_name = Public. Now this value must gets passed in the path for eg: Path =C:\Users\Public\. And from this Path I want to display all the files in the same form as they are saved.
In my current implementation I m getting list of files in base64 form.But i want in the Same form as they are saved.for eg. if file is in jpg want to display list of jpg's file.
I m getting list of files in base64 form .
public List<Image> GetImagesBySourceKey(string ID)
{
List<Image> images = new List<Image>();
string sqlQuery = "select folder_name,Subfolder_name from Table where Id= '" +
Id+ "'";
foreach (DataRow dataRow in ExecuteQuery(sqlQuery))
{
images.Add(new Models.Image()
{
folder_name= dataRow["folder_name"].ToString(),
Subfolder_name = dataRow["Subfolder_name"].ToString()
});
DirectoryInfo d = new DirectoryInfo(#"C:\\Users\\bhagyeshc\\source\\repos\\abcd\\abcd\\" +
images[0].FileName + "\\" + Subfolder_name);
FileInfo[] Files = d.GetFiles("*.*"); //Getting files
foreach (FileInfo file in Files)
{
Image image = new Image();
var path = Path.Combine("~\\" + images[0].FileName + "\\" + Subfolder_name+ "\\" + file.Name);
image.Code = ImageBase64(path);
images.Add(image);
}
}
return images;
}
private string ImageBase64(string path)
{
path = System.Web.Hosting.HostingEnvironment.MapPath(path);
var ext = System.IO.Path.GetExtension(path);
var contents = System.IO.File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(contents);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
DirectoryInfo d = new DirectoryInfo(#"D:\"+Folder_name+"\"+SubFolder_name");
FileInfo[] Files = d.GetFiles("*.jpg"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
str = str + ","+file.Name;
}
str will return all files under this folder
i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.
i am trying to add file names in session.
the problem here is that it doesn't add multiple file names inside single session
here is my code :
string imageSessList = context.Session["imageNames"].ToString(); //if i put this line at the begining, then the debugger doesn't even moves to foreach block
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
string destFileName = "";
List<string> lstImageNames = new List<string>();
// else upload file
if (!string.IsNullOrEmpty(fileName))
{
if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
{
if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
{
// generate file name
destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
//Save image names to session
lstImageNames.Add(destFileName);
context.Session["imageNames"] = lstImageNames;
file.SaveAs(destFilePath);
strMessage = "Success " + destFileName;
}
else
{
strMessage = "File Size can't be more than 5 MB.";
}
}
else
{
strMessage = "File type not supported!";
}
}
} // foreach
context.Response.Write(strMessage);
}
here i am able to add only single filename to session, not multiple.
how to store and maintain multiple file names in single session :
context.Session["imageNames"]
you need to get current list from session
List<string> lstImageNames= (List<string>)Session["imageNames"];
if(lstImageNames==null)
lstImageNames = new List<string>(); // create new list in the first time
now add new item to it.
lstImageNames.Add(destFileName);
set back to session
context.Session["imageNames"] = lstImageNames;
I would like to copy my files from source folder to my dest. folder
The location / URL(Name of the column in the table) I got it from here GetDataByGeneralRoot();
Now I would like to copy those file from that URL to a new directory.
What I have done is:
DataSet1.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string gerneralRootPath = docTab.Rows[0]["URL"].ToString();
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 4);
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + gerneralRootPath;
foreach (string path in Directory.GetFiles(final, "*.*", SearchOption.AllDirectories))
{
string t = path.Substring(path.IndexOf("\\") + 1);
File.Copy(t, t.Replace(final + t, rootFolderAbsolutePath));
}
My issue / problem is how can I say that I want to get only the files from URL that I got from my method GetDataByGeneralRoot and not all the files what is now happening.
HERE is how my tabel looks like:
I think you want something like this
public void copyAll(DataSet ds, Doc doc, string rootPath, string rootTargetPath)
{
ds.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + rootPath;
foreach (var row in docTab.Rows)
{
var sourceFile = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/" + row["URL"].ToString();
string targetPath = rootTargetPath + row["URL"].ToString();
File.Copy(sourceFile, rootTargetPath);
}
}
I need to copy a particular file from one library to another library.
At first, need to check if file is existing in that library.
If Existing, then need to overwrite file content and new sharepoint version should be updated for that document.
I need to do this using c# CSOM and sharepoint version is 2013.
Thanks in advance :)
public static void CopyDocuments(string srcUrl, string destUrl, string srcLibrary, string destLibrary, Login _login)
{
// set up the src client
SP.ClientContext srcContext = new SP.ClientContext(srcUrl);
srcContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
srcContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);
// set up the destination context (in your case there is no needs to create a new context, because it would be the same library!!!!)
SP.ClientContext destContext = new SP.ClientContext(destUrl);
destContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
destContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);
// get the list and items
SP.Web srcWeb = srcContext.Web;
SP.List srcList = srcWeb.Lists.GetByTitle(srcLibrary);
SP.ListItemCollection col = srcList.GetItems(new SP.CamlQuery());
srcContext.Load(col);
srcContext.ExecuteQuery();
// get the new list
SP.Web destWeb = destContext.Web;
destContext.Load(destWeb);
destContext.ExecuteQuery();
foreach (var doc in col)
{
try
{
if (doc.FileSystemObjectType == SP.FileSystemObjectType.File)
{
// get the file
SP.File f = doc.File;
srcContext.Load(f);
srcContext.ExecuteQuery();
// build new location url
string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + f.Name;
// read the file, copy the content to new file at new location
SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
}
if (doc.FileSystemObjectType == SP.FileSystemObjectType.Folder)
{
// load the folder
srcContext.Load(doc);
srcContext.ExecuteQuery();
// get the folder data, get the file collection in the folder
SP.Folder folder = srcWeb.GetFolderByServerRelativeUrl(doc.FieldValues["FileRef"].ToString());
SP.FileCollection fileCol = folder.Files;
// load everyting so we can access it
srcContext.Load(folder);
srcContext.Load(fileCol);
srcContext.ExecuteQuery();
foreach (SP.File f in fileCol)
{
// load the file
srcContext.Load(f);
srcContext.ExecuteQuery();
string[] parts = null;
string id = null;
if (srcLibrary == "My Files")
{
// these are doc sets
parts = f.ServerRelativeUrl.Split('/');
id = parts[parts.Length - 2];
}
else
{
id = folder.Name;
}
// build new location url
string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + id + "/" + f.Name;
// read the file, copy the content to new file at new location
SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
}
}
}
catch (Exception ex)
{
Log("File Error = " + ex.ToString());
}
}
}
Source: https://sharepoint.stackexchange.com/questions/114033/how-do-i-move-files-from-one-document-library-to-another-using-jsom
I strongly advise against using the approach suggested by Nikerym. You don't want to download the bytes only to upload them unmodified. It's slow and error-prone. Instead, use the built-in method provided by the CSOM API.
https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-server/mt162553(v=office.15)?redirectedfrom=MSDN
var srcPath = "https://YOUR.sharepoint.com/sites/xxx/SitePages/Page.aspx";
var destPath = $"https://YOUR.sharepoint.com/sites/xxx/SitePages/CopiedPage.aspx";
MoveCopyUtil.CopyFileByPath(ctx, ResourcePath.FromDecodedUrl(srcPath), ResourcePath.FromDecodedUrl(destPath), false, new MoveCopyOptions());
ctx.ExecuteQuery();
You can configure the override behavior by adjusting the 4th and 5th arguments of the function signature.
[...]
bool overwrite,
MoveCopyOptions options
https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-server/mt844930(v=office.15)
Can someone help me, I just learning C# for about 2 month, I have this problem,
i'm building a class for filter data from temp file and create the result in new txt file inside directory, if directory is empty nor at the same date, it build perfectly, and if there another file at same date it should create with increase the last number at lastname.
My problem when I run code, it is not creating if the directory has files with the same dates, then the result should be something like this:
C:\result_2014051301.txt
C:\result_2014051401.txt
C:\result_2014051402.txt <-- Failed, it is not ..2014051401.txt
class Entity2
{
public Entity2()
{
string fileTemp = "DEFAULT.temp";
string indexD = Properties.Settings.Default.ChIndex2D;
string indexC = Properties.Settings.Default.ChIndex2C;
string indexS = Properties.Settings.Default.ChIndex2S;
string tempPath = AppDomain.CurrentDomain.BaseDirectory;
string targetPath = Properties.Settings.Default.ExtractALL_DIR;
string SourceFile = Path.Combine(tempPath, fileTemp);
string tempFileX = Path.GetTempFileName();
if (!System.IO.Directory.Exists(targetPath))
{
System.Windows.Forms.MessageBox.Show("Error missing .temp", "Message Box");
}
else
{
string ext = ".txt";
int sequence = 0;
DateTime dateFileName = DateTime.Today;
string discode = Properties.Settings.Default.ChannelID_2;
string filename = discode + "_" + dateFileName.ToString("yyyyMMdd");
string pathX = Properties.Settings.Default.ExtractALL_DIR + #"/Channel2";
if (!Directory.Exists(pathX))
{
Directory.CreateDirectory(pathX);
}
string[] files = Directory.GetFiles(pathX, filename + "*.txt", SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
Array.Sort(files);
string lastFilename = files[files.Length - 1];
sequence = Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
}
sequence++;
string newFileName = filename + sequence.ToString().PadLeft(2, '0') + ext;
string DestFile = Path.Combine(pathX, newFileName);
using (var ab = new StreamReader(SourceFile))
using (var cd = new StreamWriter(DestFile))
{
string lineX;
while ((lineX = ab.ReadLine()) != null)
{
if (lineX.LastIndexOf("100", 3) != -1 || lineX.LastIndexOf("MGR", 15) != -1 || lineX.LastIndexOf(indexC, 15) != -1)
{
lineX = lineX.Replace(indexD, "");
lineX = lineX.Replace("DEFAULT", discode);
if (lineX.LastIndexOf("800", 3) != -1)
{
lineX = lineX.Replace(indexS, "");
}
cd.WriteLine(lineX);
}
}
}
}
}
}
This piece is not functioning correctly:
Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
pathX + filename is C:\folderfile.txt not C:\folder\file.txt.
You either need to add the \ or call Path.Join.
That will cause the Parse operation to fail since it tries to consume the who string (minus the extension).