I've this folder and I want to get a specific file from it, how can I do that given that there could be more than one file in there.
I've tried to use StartsWith but wasn't able to do so, is there any way this could be done?
The file is in the CustomerWorkSheet folder and its name starts with the customer id field value. What should I use if I have this path: .../uploads/attachments/CustomerWorkSheet/**File Name Here**
IWordDocument doc = new WordDocument();
doc.Open(
System.Web.HttpContext.Current.Server.MapPath
("~/Content/uploads/attachments/CustomerWorkSheet/"),
FormatType.Doc);
I need some thing like that
if(file.StartsWith(customerId))
but couldn't get the file
var directoryPath = System.Web.HttpContext.Current.Server.MapPath("~/Content/uploads/attachments/CustomerWorkSheet");
var file = Directory.EnumerateFiles(directoryPath).SingleOrDefault(f => f.Contains("CustomerWorkSheet/" + myCustomerId));
if(file != null){
IWordDocument doc = new WordDocument();
doc.open(file, FormatType.Doc);
}
Based on your comments, you are looking for this:
var filename = myDirectoryFiles.SingleOrDefault(f => f.Contains("CustomerWorkSheet/" + myCustomerId + "."));
Related
I'm having quite the time trying to get this seemingly simplistic line of code to work using C#. Trying to get a list of all my files in my repo.
File structure below:
MyRepo
-directory_01
--myFile_01.jpg
--myFile_02.jpg
This line of code lists all my directories and works great:
var streamTask = client.GetStringAsync(https://myURL/api/v4/projects/myRepo/repository/tree?private_token=myToken"
According to the api, to get my files only I should use files/:file_path attribute or archive.<file extension> to get my files.
//Get all .jpg files
var streamTask = client.GetStringAsync(https://myURL/api/v4/projects/myRepo/repository/archive.jpg?private_token=myToken"
OR
//Get one file
var streamTask = client.GetStringAsync(https://myURL/api/v4/projects/myRepo/repository/files/directory_01%2FmyFile_01%2Ejpg?private_token=myToken"
//result: 404
When you this API you also need to pass the branch name
Change
var streamTask = client.GetStringAsync(https://myURL/api/v4/projects/myRepo/repository/files/directory_01%2FmyFile_01%2Ejpg?private_token=myToken"
To
var streamTask = client.GetStringAsync(https://myURL/api/v4/projects/myRepo/repository/files/directory_01%2FmyFile_01%2Ejpg?private_token=myToken&ref=<branch_name>"
Just in case anyone else runs into this issue, here's a way to do this:
// Get list of files***********
string treeUri = $"{project}tree?private_token={projectToken}&ref=master";
string treeData = await client.GetStringAsync(treeUri);
List<AssetEntry> json = System.Text.Json.JsonSerializer.Deserialize<List<AssetEntry>>(treeData);
Console.WriteLine("FILE LIST:\n");
foreach (var item in json)
{
Console.WriteLine(item.name + " " );
}
I would make a simple program in C# with Windows forms, which gets some data given by the user thanks to some textboxes, and when He presses a button, a dialog (I don't know which one) is displayed, in order to explore the pc folders and choose a destination for saving it there.
Well, I used a FolderBrowserDialog (I don't know if that's the right one for the purpose), but there's a problem: in order to store a PDF with itext7, I have to give an Environment.SpecialFolder variable, while the method selectedPath() to get the user path of the formBrowserDialog returns a string.
I tried to convert the string into Environment.SpecialFolder in some way, but I always get a System.ArgumentException
Here's my code:
string name = txtName.Text;
//
//bla bla bla getting the parameters given by the user
//...
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
string folder="";
//"fbd" is the FolderBrowserDialog
if (fbd.ShowDialog() == DialogResult.OK)
{
//here I get the folder path (I hope I've chosen the right dialog for this scope, which is a FolderBrowserDialog)
folder = fbd.SelectedPath;
//starting my pdf generation
//here is my attempt to write something in order to parse the path string into an Environment.SpecialFolder type, to use it as a parameter in getFolderPath()
Environment.SpecialFolder path = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), folder);
//here it's supposed to give to the GetFolderPath method the Environment.SpecialFolder type.
var exportFolder = Environment.GetFolderPath(path); //ON THIS LINE I GET THE EXCEPTION
var exportFile = System.IO.Path.Combine(exportFolder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("
//bla bla bla writing my things on it
"));
}
}
//pdf creation ends
}
To simplify all of this, you don't need to Environment.SpecialFolder variable at all, nor do you need to pass it as a parameter.
The reason that an exception was thrown is because you tried to parse a string into an Environment.SpecialFolder variable enum, when the string could not be parsed into one.
You can look here to see the list of enums included. I would wager that the specific path you selected matches none of those.
Here's what your code is currently doing:
Selecting a path
Trying to parse that path to get an enum for a
special folder
Trying to get the string associated with that
Environment.SpecialFolder variable (so if you had actually been
able to parse it, you would've ended up with just what you started
with)
Combining that string with the name you wanted to give the PDF.
You can simplify all of this by omitting steps 2 and 3, which cause the error.
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
//You select the folder here
if (fbd.ShowDialog() == DialogResult.OK)
{
string folder = fbd.SelectedPath;
//combine the path of the folder with the pdf name
string exportFile = System.IO.Path.Combine(folder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("//bla bla bla writing my things on it"));
}
}
//Pdf creation ends
}
I'm writing my first Cocoa app in c#, its suppose to append/add numbers at the begging of a file name.
Users give only the path to the folder (for example with music), and for each file included in folder the program suppose to add incrementing numbers like
001_(old_fileName),
002_(old_fileName),
...,
092_(old_fileName)
etc,
Untill the end of files in given folder (by path).
There is no way to split a file name, cause file names are not known (may even include numbers itself). I've tried few possible options to solve this, but non of them works. Found few already asked question with changing names in c# but non of the results actually helped me.
The code under is the rest I've got at the moment, all non-working tries were firstly commented and later deleted. by NSAlert i see the path/name of each file in folder as a help. I would be more than happy to receive help
void RenameFunction()
{
string sPath = _Path_textBox.StringValue;
if (Directory.Exists(sPath))
{
var txtFiles = Directory.EnumerateFiles(sPath);
var txt2Files = Directory.GetFiles((sPath));
string fileNameOnly = Path.GetFileNameWithoutExtension(sPath);
string extension = Path.GetExtension(sPath);
string path = Path.GetDirectoryName(sPath);
string newFullPath = sPath;
int count = 1;
while (File.Exists(sPath))//newFullPath))
{
string tempFileName = string.Format(count + "_" + fileNameOnly + sPath);
//count++;
//string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
newFullPath = Path.Combine(path, extension + tempFileName);
count++;
}
string[] fileEntities = Directory.GetFiles(newFullPath); //GetFileSystemEntries(sPath);//GetFiles(sPath);
//foreach (var _songName in fileEntities)
//{
// string tempFileName = count + "_" + fileNameOnly + sPath;
// //string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
// newFullPath = Path.Combine(sPath ,extension + tempFileName);
// File.Move(sPath, newFullPath);
//}
foreach (var _songName in fileEntities)
{
AmountofFiles(_songName);
}
}
}
void AmountofFiles(string path)
{
var alert2 = new NSAlert();
alert2.MessageText = "mp3";
alert2.InformativeText = "AMOUNT OF MP3 FILES IS '{1}' : " + path;
alert2.RunModal();
}
Have you try use File.Move? Just move file to same path, but another name
File.Move("NameToBeRename.jpg","NewName.jpg");
There are multiple things which are not right with the code you share. The thing which want to achieve can be implemented using very simple approach.
All you need to do is retrieve all the files names with the full path from the directory and rename them one by one.
Follow the below code which demonstrates the above mentioned approach.
// Path of the directory.
var directroy = _Path_textBox.StringValue;
if (Directory.Exists(directroy))
{
//Get all the filenames with full path from the directory.
var filePaths = Directory.EnumerateFiles(directroy);
//Variable to append number in front of the file name.
var count = 1;
//Iterate thru all the file names
foreach (var filePath in filePaths)
{
//Get only file name from the full file path.
var fileName = Path.GetFileName(filePath);
//Create new path with the directory path and new file name.
var destLocation = Path.Combine(directory, count + fileName);
//User File.Move to move file to the same directory with new name.
File.Move(filePath, destLocation);
//Increment count.
count++;
}
}
I hope this helps you to resolve your issue.
I want to upload an image to a specific folder and if that folder does not exist create it and make this folder shareable to another email address.
I use the below code:
MetadataChangeSet changeSetfile = new MetadataChangeSet.Builder()
.SetTitle("Test.jpg")
.SetMimeType("image/jpeg")
.Build();
MetadataChangeSet changeSetfolder = new MetadataChangeSet.Builder()
.SetTitle("New folder")
.SetMimeType(DriveFolder.MimeType)
.SetStarred(true)
.Build();
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFolder(_googleApiClient, changeSetfile) ;
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFile(_googleApiClient, changeSetfolder, contentResults.DriveContents);
First, you have to check if the folder exist. According to this tutorial - Search files on Google Drive with C#, you can use:
By file name
What if you know the name of the file or part of the name well you can search on name. Fulltext is also nice it allows you to search on “Full text of the file including name, description, content, and indexable text.”
List files only directories
It is also possible to search for only one type of file say you just want to return all the Google sheets on your account? What if you just wanted to find all the folders well folders is a mimetype of “application/vnd.google-apps.folder” so we can search on just that.
Upon check if it is existing, get the ID to be place in the parents parameter:
var folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
var fileMetadata = new File()
{
Name = "photo.jpg",
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
Hope this helps.
I have an problem loading an xml from a path, because on my pc(and others) part of the path is mapped:
This is the path i have from the database:
\serverName\files\System\Appldata\Application\3_5\TEST\Program\Version.xml
But on my computer the path looks like this:
Y:\Application\3_5\TEST\Program
This is the code:
var path = new DirectoryInfo(x.LocationName+#"\"+x.FolderName);
var doc = new XmlDocument();
//Loading the file
doc.Load(path.FullName + #"\Version.xml");
Are there any way around this problem?
Well, do not try to concatenate by yourself the path and the filename.
Use Path.Combine
doc.Load(Path.Combine(path.FullName, "Version.xml"));
This requires the using System.IO; at the beginning of your source file.
Of course you could use both the mapped version or the full sharename only if you have the permissions to you remote folder. Also, if your database keeps the full sharename be sure that it is stored with the two initial backslash
EDIT Seeing your edit now, again, do not manually build your paths (and check if the info are valid)
var path = new DirectoryInfo(Path.Combine(x.LocationName, x.FolderName));
if(!path.Exists)
{
MessageBox.Show("Invalid path retrieved:" + path.FullName);
return;
}
var doc = new XmlDocument();
doc.Load(Path.Combine(path.FullName,"Version.xml"));
You are accessing the file using network path. Please make sure that you are able to access the file from the file explorer on webserver.
Try this code:
var doc = new XmlDocument();
var finalPath = Path.Combine(x.LocationName, x.FolderName, "Version.xml");
//Loading the file
doc.Load(finalPath);