I am trying to make a web server in C#, i need to get the requested url and then list the files and folders requested.This is good to get the first directory .
For Eg. My webserver root is c:\test when i open localhost i get the contents of test folder. Say Data is subfolder of c:\test, i can click on data from the browser and get into C:\test\data now when i click on any folder then the get request comes with %2F instead of c:\test\data\ok and so i am stuck.
Code to Recieve The Request :
sRequest = sBuffer.Substring(0, iStartPos - 1);
sRequest.Replace("\\", "/");
if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);
if (sDirName == "/")
sLocalDir = sMyWebServerRoot;
else
{
//Get the Virtual Directory
// sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);
Console.WriteLine("i am here");
sDirName = sDirName.Substring(1, sDirName.Length - 2);
//sDirName = sDirName.Replace("/", "\\");
Console.WriteLine("Amit:" + sDirName);
string test1 = Path.Combine("C:\\test\\", sDirName);
sLocalDir = Path.Combine(#"C:\\test", sDirName);
}
Now to List Dir I have the following Function :
public String listdir(string sLocaldir,string sDirName)
{
string sresult = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<head>");
sb.AppendLine("<title>Test</title>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<h1><center><u>Listing Folders Under " + sLocaldir + "</h1></u></center>");
string[] folderpaths = Directory.GetDirectories(sLocaldir);
sb.AppendLine("<font color=red><font size=5>Listing Directories<br>");
for (int i = 0; i < folderpaths.Length; i++)
{
string fpath = folderpaths[i];
string[] foldernames = fpath.Split('\\');
int j = foldernames.Length - 1;
string fname = foldernames[j];
string fullname;
if (sDirName != "/")
{
//fname= fname + "\\";
fullname = sDirName +"/"+ fname;
//fullname = fullname.Replace("\\", "/");
//fullname = Path.GetPathRoot("C:\\test");
Console.WriteLine("Get full path:" + fullname);
}
else
{
fullname = fname;
}
Console.WriteLine("Full Test:" + fullname);
//sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(fullname )),
HttpUtility.HtmlEncode(fname)));
}
string[] filePaths = Directory.GetFiles(#"C:\test");
sb.AppendLine("<font color=red><font size=5>Listing Files<br>");
for (int i = 0; i < filePaths.Length; ++i)
{
string name = Path.GetFileName(filePaths[i]);
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(name)),
HttpUtility.HtmlEncode(name)));
}
sb.AppendLine("</ul>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
sresult = sb.ToString();
return sresult;
//Console.WriteLine(sresult);
}
Any help would be highly appreciated.
Thank you
%2F is safe encoding for the / symbol. You are HTMLEncoding the / symbol in your code above.
Your approach can be much simpler see:
http://www.codeproject.com/KB/IP/mywebserver.aspx
Related
I am new to C# and I am trying to go through each cell within a Column. I always get the "errorCS0021 Cannot apply indexing with [] to an expression of type 'Range' AnlagenSites". What do I have to change in my code?
static void Main() {
//getting Data from Excel Files
WorkBook wb = WorkBook.Load("D:\\SoftwareSolutions\\AnlagenSites\\AnlagenSites\\AnlagenSites\\2022.08.18 - DoubleCheckFS20.xlsx");
WorkSheet sheet = wb.GetWorkSheet("2022.08.18 - DoubleCheckFS20");
var Site = sheet["A1:A2"];
Console.WriteLine(Site);
var Number = sheet["B1:B2"];
for(var i =1; i <= Site.Count(); i++)
{
Site[i];//here is the error
Number[i]; // same error here
string fileName = "Test.txt";
string sourcePath = "D:\\SoftwareSolutions\\AnlagenSites\\AnlagenSites\\AnlagenSites";
//putting string together
string Bregenz = "Bregenz";
for (int j = 1; j < Site.Count(); j++)
{
string targetPath = "";
if (Site.Count(j) == Bregenz)
{
targetPath = "\\ad001\\" + Number[j] + "\\other";
}
else
{
targetPath = #"\\ad001\\" + Site[j] + "\\" + Number[j] + "\\other";
}
Console.WriteLine("Protokoll added to Site:" + Site[j] + " number:" + Number[j]);
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
.
.
.
I got all the ID in a .txt files, my program read the file and store all the ID in a table of String.
What I want to do now, is get the full Path of the files containing the ID in the name and then move it in an other Directory.
I've tried this way and many other things, but doesn't seem to be working.
Console.WriteLine("" + lines[i]);
string fullPath = "Path.GetFullPath(#"C:\Users\Desktop\Script\tiptop\");
Console.WriteLine("" + fullPath.Contains(lines[i]));"
static void Main(string[] args)
{
string ID = File.ReadAllText(#"C:\Users\Desktop\Script\zig.txt");
Console.WriteLine(ID);
Console.ReadLine();
string[] lines = File.ReadAllLines(#"C:\Users\Desktop\Script\zig.txt");
for (int i = 0; i <= lines.Length;i++)
{
Console.WriteLine("" + lines[i]);
string fullPath = Path.GetFullPath(#"C:\Users\Desktop\Script\tiptop\");
Console.WriteLine("" + fullPath.Contains(lines[i]));
}
}
Are the files all in the tiptop level directory? OR are they a subdirectories under tiptop?
if top-level, does this help;
String root = #"C:\Users\Desktop\Script\tiptop\";
String[] lines = System.IO.File.ReadAllLines(#"C:\Users\Desktop\Script\zig.txt");
for (int i = 0; i <= lines.Length; i++)
{
string fullPath = System.IO.Path.Combine(root, lines[i]);
if (System.IO.File.Exists(fullPath)) {
// Do something...
}
}
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)
{
}
}
Is it any possible way to create a video thumbnail from random url?
I have some links with video and I want to make a thumbnail from that video and save the thumbnail image on local storage. If any possible way to do this ?
Here is the solution for youtube videos:-
public string GetThumbnailsUrl(string url)// this url is your youtube video url
{
string imgurl = "";
if (url != "")
{
if (!url.ToLower().Contains("embed/"))//if not an embed URL
{
string v = url;
if (url.Contains("?"))
{
v = v.Substring(v.LastIndexOf("v=") + 2);
if (v.Contains("&"))
v = v.Substring(0, v.LastIndexOf("&"));
}
else
{
v = v.Substring(v.LastIndexOf("v/") + 2);
}
int i = 0;
try
{
i = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSize"].Trim());//ImageSize contains the size of image.... the value is like 0,1,2,3.....
}
catch { i = 0; }
imgurl = "http://img.youtube.com/vi/" + v + "/" + i + ".jpg";
}
else//For embed URL
{
string[] sep = new string[1] { "embed/" };
string[] ss = url.Split(sep, StringSplitOptions.None);
string key = ss[ss.Length - 1];
int i = 0;
try
{
i = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSize"].Trim());
}
catch { i = 0; }
imgurl = "http://img.youtube.com/vi/" + key + "/" + i + ".jpg";
}
}
return imgurl;
}
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).