how not to overwrite in FileUpload in C# - c#

in the code below
public class UploadController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
postedFile.SaveAs(filePath);
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
docfiles.Add(filePath + fileName);
// docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
I really want to make a file upload the classic filename(1).jpg if file name is already exists but the code I had still delete the old files that has the same name, I don't know where I got it wrong i used while loop but it wasnt working

I tried fixing it the code below is working now it turns out i constructed it wrong :)
var filePath = HttpContext.Current.Server.MapPath("~/Files/" );
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
postedFile.SaveAs(filePath + fileName);

Related

can't use replace function when upload files API on asp.net core 2.2

I work on ASP.NET Core 2.2 Web API and face an issue: I can't use replace function to change the name property of a selected file that I get when uploaded.
When I try like this:
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
I get an error
Iform file doesn't contain definition for replace and no accessible extension method Replace accepting first argument of iformfile
Full sample is here:
[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
try
{
var DisplayFileName = Request.Form.Files[0];
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
string Month = DateTime.Now.Month.ToString();
string DirectoryCreate = myValue1 + Month;
Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (!Directory.Exists(DirectoryCreate))
{
Directory.CreateDirectory(DirectoryCreate);
}
if (DisplayFileName.Length > 0)
{
var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
var dbPath = Path.Combine(DirectoryCreate, fileName);
using (var stream = new FileStream(dbPath, FileMode.Create))
{
Request.Form.Files[0].CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
How to solve this issue?
sample
suppose i select file developed.xlsx
then after use replace or any way result will be
developed-sddfn78888.xlsx
You can use System.IO.Path to get filename and get file extension from request files.
Change this
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
To
string filename = Path.GetFileName(DisplayFileName.FileName);
string fileExtension = Path.GetExtension(DisplayFileName.FileName);
string newFileName = $"{filename}-{Guid.NewGuid().ToString()}{fileExtension}";
Otherwise, you could modify your code to
string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

Creating Folders dynamically using CSOM in sharepoint causes ID issues for the document

I am creating the nested folders dynamically for a document library and uploading files. The below code is working fine. but the issues is whenever i uploading the file to the existence folder the ID of the document for the uploaded documents is not in sequence. Suppose if i am uploading a file to path projects\PRJ1\Assignment, fist time it was creating the folders and file with ID's(1\2\3\4) respectively . If i upload other document to the same folder the id of the folders is not changing but the id of the file is 8. i am not unable to find the id 5,6,7 in the document library.
using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
clientContext.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
CSOM.Web _Site = clientContext.Web;
// string listrootfolder = "Testlist";
CSOM.List _List = _Site.Lists.GetByTitle("Testlist");
clientContext.Load(_List.RootFolder);
clientContext.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
var folder = CreateFolder(clientContext.Web, "Testlist", folderpath);
// uploading the document
CSOM.FileCreationInformation newFile = new CSOM.FileCreationInformation();
// newFile.Content = System.IO.File.ReadAllBytes(#"D:\Testupload.docx");
byte[] bytes = Convert.FromBase64String(objReqDocumentDetials.FileData.ToString());
newFile.Content = bytes;
// newFile.Url = objDocumentDetials.AttachmentName.ToString() + DateTime.Now.ToString("ddMMyyyyHHmmsss") + "." + objDocumentDetials.FileType.ToString();
newFile.Url = objReqDocumentDetials.FileName.ToString() + "." + objReqDocumentDetials.FileType.ToString();
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File _UploadingFile = folder.Files.Add(newFile);
var item = _UploadingFile.ListItemAllFields;
// var folder = item.GetFolder("account/" + folderName);
// item["Year"] = DateTime.Now.Year.ToString();
// item.Update();
clientContext.Load(_UploadingFile, f => f.ListItemAllFields);
clientContext.ExecuteQuery();
}
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
CSOM.List list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
public CSOM.Folder CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
The issue was fixed after redefined the CreateFolder and CreateFolderInternal methods as below
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
CSOM.List _List = web.Lists.GetByTitle(listTitle);
web.Context.Load(_List.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
string root = "";
for (int i = 0; i < folderUrls.Length; i++)
{
root = folderUrls[i].ToString();
string targetFolderUrl = "/" + listrootfolder + "/" + string.Join("/", folderUrls, 0, i + 1);
var folder1 = web.GetFolderByServerRelativeUrl(targetFolderUrl);
web.Context.Load(folder1);
bool exists = false;
try
{
web.Context.ExecuteQuery();
exists = true;
}
catch (Exception ex)
{
}
if (!exists)
{
if (i == 0)
{
CreateFolderInternal(web, _List.RootFolder, root);
}
else
{
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
var targetfolderUrls = targetFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string jj = string.Join("/", targetfolderUrls, 0, targetfolderUrls.Length - 1);
CSOM.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + jj);
web.Context.Load(folder);
web.Context.ExecuteQuery();
SPCreateFolderInternal(web, folder, root);
}
}
else
{
//already folder exists
}
}
CSOM.Folder finalfolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + listrootfolder + "/" + fullFolderPath);
web.Context.Load(finalfolder);
web.Context.ExecuteQuery();
return finalfolder;
}
private void CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
try
{
var curFolder = parentFolder.Folders.Add(fullFolderPath);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
}
catch (System.Exception ex)
{
}
}

Convert from a DataUrl to an Image in C# and write a file with the bytes

Hello I have signature like this:
which is encoded to a DataUrl specifically this string:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs... (long string)"
What i want to do is Convert this DataUrl to an PNG Image, and save the image to the device, this is what i am doing so far:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(path, base64Data);
if (!File.Exists(filename))
{
using (var stream = new MemoryStream(binData))
{
//Code crashing here--------------------------
File.WriteAllBytes(filename, binData);
}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
But my code is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
Any Ideas?
As #SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//filename = Path.Combine(path, base64Data.Replace(#"/", string.Empty));
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
string fileName = "Sn" + milliseconds.ToString() + ".PNG";
filename = Path.Combine(path, fileName);
if (!File.Exists(filename))
{
//using (var stream = new MemoryStream(binData))
//{
File.WriteAllBytes(filename, binData);
//}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
And the image showed:
I just cleaned Mario's code and fine tuned regex:
public string SaveDataUrlToFile(string dataUrl, string savePath)
{
var matchGroups = Regex.Match(dataUrl, #"^data:((?<type>[\w\/]+))?;base64,(?<data>.+)$").Groups;
var base64Data = matchGroups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
System.IO.File.WriteAllBytes(savePath, binData);
return savePath;
}

C# fail to create file in directory if has other file

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).

Categories