这是一篇记录平常工作笔记的博客,无论是在排版还是解说上都不会有太多要求。同时这也是一篇不上博客园首页的博客,Just记录一些工作笔记。
var allFiles = Directory.GetFiles(@"D:\TestFolder"); string dataIsNull = @"D:\dataisnull.txt"; string matchLog = @"D:\matchLog.txt"; foreach (var filePath in allFiles)
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs); //string fileContent = sr.ReadToEnd(); //encoding = sr.CurrentEncoding; //记录每次读取的一行记录
string strLine = ""; //记录每行记录中的各字段内容
string[] aryLine = null; string[] tableHead = null; //标示列数
int columnCount = 0; //标示是否是读取的第一行
bool IsFirst = true; //逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{ if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length; //创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
} else {
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow(); if (aryLine.Length == columnCount)
{ for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
}
dt.Rows.Add(dr);
}
} if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}
sr.Close();
fs.Close(); if (dt.Rows.Count == 0)
{
OutputLog(dataIsNull, string.Format("{0} data is null.", filePath)); continue;
}
StringBuilder mpAttributesLog = new StringBuilder();
StringBuilder allLog = new StringBuilder(); foreach (DataRow item in dt.Rows)
{ string mpAttributes = item["MPAttributes"].ToString(); var mpAttributesList = mpAttributes.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); string metaFeatures = item["MetaFeatures"].ToString().ToUpper(); string sha1 = item["Sha1"].ToString(); foreach (var mpAttributesItem in mpAttributesList)
{ if (!metaFeatures.Contains(mpAttributesItem.ToUpper().Trim()))
{
mpAttributesLog.AppendFormat("{0};", mpAttributesItem);
}
} //allLog.AppendLine(string.Format("{0}\n{1}\n{2}\n", mpAttributesLog.ToString(), sha1, metaFeatures));
if (mpAttributesLog.Length != 0)
{ using (StreamWriter sw = File.AppendText(matchLog))
{
sw.WriteLine(mpAttributesLog.ToString());
sw.WriteLine(sha1);
sw.WriteLine(metaFeatures);
}
}
} //if (mpAttributesLog.Length != 0) //{ // OutputLog(matchLog, string.Format("{0} data is null.", allLog.ToString())); //}
}
/\*\*/
/// <summary>
/// 水印位置 /// </summary>
public enum ImagePosition
{ /\*\*/
/// <summary>
/// 左上 /// </summary>
LeftTop, /**/
///
LeftBottom, /**/
///
RightTop, /**/
///
RigthBottom, /**/
///
TopMiddle, /**/
///
BottomMiddle, /**/
///
Center
} /**/
///
class ImageWater_Word
{ private string _ErrMsg; #region 出错信息
/**/
///
public string ErrMsg
{ get { return _ErrMsg; } set { _ErrMsg = value; }
} #endregion
#region 将文件转换成流
//public byte[] SetImageToByteArray(string fileName, ref string fileSize)
/**/
///
/// 文件全路径
///
private byte[] SetImageToByteArray(string fileName)
{ byte[] image = null; try {
FileStream fs = new FileStream(fileName, FileMode.Open);
FileInfo fileInfo = new FileInfo(fileName); //fileSize = Convert.ToDecimal(fileInfo.Length / 1024).ToString("f2") + " K";
int streamLength = (int)fs.Length;
image = new byte[streamLength];
fs.Read(image, 0, streamLength);
fs.Close(); return image;
} catch { return image;
}
} #endregion
#region 将byte转换成MemoryStream类型
/**/
///
/// byte[]变量
///
private MemoryStream ByteToStream(byte[] mybyte)
{
MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length); return mymemorystream;
} #endregion
#region 将byte转换成Image文件
/**/
///
/// byte[]变量
///
private System.Drawing.Image SetByteToImage(byte[] mybyte)
{
System.Drawing.Image image;
MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
image = System.Drawing.Image.FromStream(mymemorystream); return image;
} #endregion
#region 批量在图片上添加透明水印文字
/**/
///
/// 原来图片地址(路径+文件名)
/// 需要添加到图片上的文字
/// 透明度(0.1~1.0之间)
/// 文字显示的位置
/// 是否覆盖原图片(如果不覆盖,那么将在同目录下生成一个文件名带0207的文件)
///
public bool DrawWords(string[] arrsourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
{ foreach (string imgPath in arrsourcePicture)
{ if (!DrawWord(imgPath, waterWords, alpha, position, fRewrite))
{
_ErrMsg += "——处理文件:" + imgPath + " 时出错。"; return false;
}
} return true;
} #endregion
#region 在图片上添加透明水印文字
/**/
///
/// 原来图片地址(路径+文件名)
/// 需要添加到图片上的文字
/// 透明度(0.1~1.0之间)
/// 文字显示的位置
/// 是否覆盖原图片(如果不覆盖,那么将在同目录下生成一个文件名带0207的文件)
///
public bool DrawWord(string sourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
{ if (!System.IO.File.Exists(sourcePicture))
{
_ErrMsg = "文件不存在!"; return false;
} string fileExtension = System.IO.Path.GetExtension(sourcePicture).ToLower(); if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
{
_ErrMsg = "不是图片文件!"; return false;
}
Image imgPhoto = null;
Bitmap bmPhoto = null;
Graphics grPhoto = null; try { //创建一个图片对象用来装载要被添加水印的图片
imgPhoto = Image.FromStream(ByteToStream(SetImageToByteArray(sourcePicture))); //获取图片的宽和高
int phWidth = imgPhoto.Width; int phHeight = imgPhoto.Height; //建立一个bitmap,和我们需要加水印的图片一样大小
bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); //SetResolution:设置此 Bitmap 的分辨率 //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); //Graphics:封装一个 GDI+ 绘图图面。
grPhoto = Graphics.FromImage(bmPhoto); //设置图形的品质
grPhoto.SmoothingMode = SmoothingMode.AntiAlias; //将我们要添加水印的图片按照原始大小描绘(复制)到图形中
grPhoto.DrawImage(
imgPhoto, // 要添加水印的图片
new Rectangle(0, 0, phWidth, phHeight), // 根据要添加的水印图片的宽和高
0, // X方向从0点开始描绘
0, // Y方向
phWidth, // X方向描绘长度
phHeight, // Y方向描绘长度
GraphicsUnit.Pixel); // 描绘的单位,这里用的是像素 //根据图片的大小我们来确定添加上去的文字的大小 //在这里我们定义一个数组来确定
int[] sizes = new int[] { 48, 36, 28, 24, 16, 14, 12, 10 }; //字体
Font crFont = null; //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空
SizeF crSize = new SizeF(); //利用一个循环语句来选择我们要添加文字的型号 //直到它的长度比图片的宽度小
for (int i = 0; i < sizes.Length; i++)
{
crFont = new Font("arial", sizes[i], FontStyle.Bold); //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。
crSize = grPhoto.MeasureString(waterWords, crFont); // ushort 关键字表示一种整数数据类型
if ((ushort)crSize.Width < (ushort)phWidth) break;
} //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
int yPixlesFromBottom = (int)(phHeight * .05); //定义在图片上文字的位置
float wmHeight = crSize.Height; float wmWidth = crSize.Width; float xPosOfWm; float yPosOfWm; //设置水印的位置
switch (position)
{ case ImagePosition.BottomMiddle:
xPosOfWm = phWidth / 2;
yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.Center:
xPosOfWm = phWidth / 2;
yPosOfWm = phHeight / 2; break; case ImagePosition.LeftBottom:
xPosOfWm = wmWidth;
yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.LeftTop:
xPosOfWm = wmWidth / 2;
yPosOfWm = wmHeight / 2; break; case ImagePosition.RightTop:
xPosOfWm = phWidth - wmWidth - 10;
yPosOfWm = wmHeight; break; case ImagePosition.RigthBottom:
xPosOfWm = phWidth - wmWidth - 10;
yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.TopMiddle:
xPosOfWm = phWidth / 2;
yPosOfWm = wmWidth; break; default:
xPosOfWm = wmWidth;
yPosOfWm = phHeight - wmHeight - 10; break;
} //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。
StringFormat StrFormat = new StringFormat(); //定义需要印的文字居中对齐
StrFormat.Alignment = StringAlignment.Center; //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。 //这个画笔为描绘阴影的画笔,呈灰色
int m_alpha = Convert.ToInt32(255 * alpha);
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0)); //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果 //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。
grPhoto.DrawString(waterWords, //string of text
crFont, //font
semiTransBrush2, //Brush
new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
StrFormat); //从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153 //这个画笔为描绘正式文字的笔刷,呈白色
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(80, 255, 255, 255)); //第二次绘制这个图形,建立在第一次描绘的基础上
grPhoto.DrawString(waterWords, //string of text
crFont, //font
semiTransBrush, //Brush
new PointF(xPosOfWm, yPosOfWm), //Position
StrFormat); //imgPhoto是我们建立的用来装载最终图形的Image对象 //bmPhoto是我们用来制作图形的容器,为Bitmap对象
imgPhoto = bmPhoto; //释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满 //grPhoto.Dispose(); //将grPhoto保存
if (fRewrite)
{
imgPhoto.Save(sourcePicture);
} else { // 目标图片名称及全路径
string targetImage = sourcePicture.Replace(System.IO.Path.GetExtension(sourcePicture), "") + "_0207" + fileExtension;
imgPhoto.Save(targetImage);
} //imgPhoto.Dispose();
return true;
} catch (Exception ex)
{
_ErrMsg = ex.Message; return false;
} finally { if (imgPhoto != null)
imgPhoto.Dispose(); if (bmPhoto != null)
bmPhoto.Dispose(); if (grPhoto != null)
grPhoto.Dispose();
}
} #endregion }
private static string localFolder = System.Configuration.ConfigurationSettings.AppSettings["localFolder"];
读txt
using (StreamReader streamReader = new StreamReader(@"E:\Test\local.txt"))
{ while ((lineLocal = streamReader.ReadLine()) != null)
{
lineLocal = lineLocal.Trim(); if (!string.IsNullOrEmpty(lineLocal))
{
localList.Add(lineLocal);
}
}
}
写txt
List<string> stringList = new List<string>(); // 覆盖原有的信息
using (StreamWriter sw = new StreamWriter(@"E:\SQLTest\Test.txt"))
{ foreach (string text in stringList)
{
sw.WriteLine(text);
}
} // 不覆盖原有的信息
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);
}
获取文件后缀名:Path.GetExtension(file)
获取文件名 称:Path.GetFileName(file)
获取文件所有文件:Directory.GetFiles(localFolder)
获取绝对路径:Path.GetFullPath(System.Configuration.ConfigurationSettings.AppSettings["localFolder"])
private static System.Data.DataTable GetExcelData(string excelFilePath)
{
Excel.Application app \= new Excel.Application();
Excel.Sheets sheets;
Excel.Workbook workbook \= null; object oMissiong = System.Reflection.Missing.Value;
System.Data.DataTable dt \= new System.Data.DataTable(); try { if (app == null)
{ return null;
}
workbook \= app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
sheets \= workbook.Worksheets;
Excel.Worksheet worksheet \= (Excel.Worksheet)sheets.get\_Item(1); if (worksheet == null) return null; string cellContent; int iRowCount = worksheet.UsedRange.Rows.Count; int iColCount = worksheet.UsedRange.Columns.Count;
Excel.Range range;
DataColumn dc; int ColumnID = 1;
range \= (Excel.Range)worksheet.Cells\[1, 1\]; while (range.Text.ToString().Trim() != "")
{
dc \= new DataColumn();
dc.DataType \= System.Type.GetType("System.String");
dc.ColumnName \= range.Text.ToString().Trim();
dt.Columns.Add(dc);
range \= (Excel.Range)worksheet.Cells\[1, ++ColumnID\];
} for (int iRow = 2; iRow <= iRowCount; iRow++)
{
DataRow dr \= dt.NewRow(); for (int iCol = 1; iCol <= iColCount; iCol++)
{
range \= (Excel.Range)worksheet.Cells\[iRow, iCol\];
cellContent \= (range.Value2 == null) ? "" : range.Text.ToString();
dr\[iCol \- 1\] = cellContent;
}
dt.Rows.Add(dr);
} return dt;
} catch { return null;
} finally {
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook \= null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app \= null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
完美解决: Retrieving the COM class factory for component with CLSID {00024500-0000-000 (未成功)
在服务器上,
1,运行dcomcnfg打开组件服务
2,依次展开"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
3,找到"Microsoft Excel应用程序"
右键打开属性对话框 点击"安全"选项卡, 把"启动和激活权限","配置权限",都选择为自定义, 然后依次点击它们的编辑,把ASPNET添加进去,并加入所有的权限..
namespace TestApp
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Info> info = new List<Info>();
info.Add(new Info() { Id ="Test1", Name ="Test1"});
info.Add(new Info() { Id ="Test1", Name ="Test1"});
info.Add(new Info() { Id ="Test2", Name ="Test2"});
info.Add(new Info() { Id ="Test3", Name ="Test3"});
info.Add(new Info() { Id ="Test3", Name ="Test3"});
info = info.Distinct(new Comparint()).ToList();
Console.WriteLine(info.Count);
}
}
public class Info
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Comparint : IEqualityComparer<Info>
{
public bool Equals(Info x, Info y)
{
if (x == null && y == null)
return false;
return x.Id == y.Id;
}
public int GetHashCode(Info obj)
{
return obj.ToString().GetHashCode();
}
}
}
SQLServer 的数据分页:
假设现在有这样的一张表:
CREATE TABLE test
(
id int primary key not null identity,
names varchar(20)
)
然后向里面插入大约1000条数据,进行分页测试
假设页数是10,现在要拿出第5页的内容,查询语句如下:
--10代表分页的大小
select top 10 *
from test
where id not in
(
--40是这么计算出来的:10*(5-1)
select top 40 id from test order by id
)
order by id
原理:需要拿出数据库的第5页,就是40-50条记录。首先拿出数据库中的前40条记录的id值,然后再拿出剩余部分的前10条元素
第二种方法:
还是以上面的结果为例,采用另外的一种方法
--数据的意思和上面提及的一样
select top 10 *
from test
where id >
(
select isnull(max(id),0)
from
(
select top 40 id from test order by id
) A
)
order by id
原理:先查询前40条记录,然后获得其最id值,如果id值为null的,那么就返回0
然后查询id值大于前40条记录的最大id值的记录。
这个查询有一个条件,就是id必须是int类型的。
第三种方法:
select top 10 *
from
(
select row_number() over(order by id) as rownumber,* from test
) A
where rownumber > 40
原理:先把表中的所有数据都按照一个rowNumber进行排序,然后查询rownuber大于40的前十条记录
这种方法和oracle中的一种分页方式类似,不过只支持2005版本以上的
第四种:
存储过程查询
创建存储过程
alter procedure pageDemo
@pageSize int,
@page int
AS
declare @temp int
set @temp=@pageSize*(@page - 1)
begin
select top (select @pageSize) * from test where id not in (select top (select @temp) id from test) order by id
end
执行存储过程
exec 10,5
手机扫一扫
移动阅读更方便
你可能感兴趣的文章